• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • VCS
  • Interview Questions
  • Database
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

How to add new host entry in /etc/hosts when a docker container is run

by admin

This post shows how to add host-entries onto /etc/hosts on docker container when it is run. For the purpose of this post, we are using CentOS/RHEL 7 host. But this should work on any Linux host capable of running latest docker versions.

Generally speaking, /etc/hosts file can not be modified before running the docker container. However, current docker has an option “–add-host” which adds host-entries onto /etc/hosts when the container is run. Below is the syntax to add host entry while creating a new docker container.

$ sudo docker run --add-host [Hostname]:[IPAddress] -ti [Source_Container_Image] /bin/bash

For example to add a new host entry (192.168.0.1 host2.test.com) use the below command:

$ sudo docker run --add-host host1.test.com:192.168.0.1 --add-host host2.test.com:192.168.0.2 -ti source_container_image /bin/bash

The example brings /etc/hosts in the new container which has host1.test.com and host2.test.com like:

[root@63933bfcd3d3 /]# cat /etc/hosts
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
192.168.0.1 host1.test.com
192.168.0.2 host2.test.com
172.17.0.4 63933bfcd3d3

[root@63933bfcd3d3 /]#

Filed Under: DevOps, Docker

Some more articles you might also be interested in …

  1. Set up Jupyter Notebook in VS Code for Data Science
  2. Python Quadratic Formula
  3. kubectl: command not found
  4. ansible-vault – Encrypts & decrypts values, data structures and files within Ansible projects
  5. How to schedule master node running pod/service as a worker node
  6. berks Command Examples (Chef cookbook dependency manager)
  7. How to write Bubble sort in Bash
  8. Is there a CSS parent selector
  9. How to Configure Network Namespaces in Docker Containers
  10. Beginners Guide to The Docker World

You May Also Like

Primary Sidebar

Recent Posts

  • gml2gv Command Examples
  • glow Command Examples
  • glib-compile-resources Command Examples
  • glances Command Examples

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright