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

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • VCS
  • Interview Questions
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • 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. How To Get Information About a Container In Docker
  2. How to find docker storage device and its size (device mapper storage driver)
  3. The Ultimate Beginner’s Guide to Static Website Hosting With Google Firebase (for FREE)
  4. How to Use External Python modules in MySQL Shell
  5. How To Access Kubernetes Dashboard Externally
  6. Docker Basics – Expose ports, port binding and docker link
  7. How to Start, Stop and Restart Zimbra Service
  8. How to Find and Delete Empty Directories and Files in Linux
  9. How to Stop and Start Ec2 instance using Jenkins
  10. Troubleshooting kubectl Error: The connection to the server x.x.x.x:6443 was refused – did you specify the right host or port?

You May Also Like

Primary Sidebar

Recent Posts

  • qm Command Examples in Linux
  • qm wait Command Examples in Linux
  • qm start Command Examples in Linux
  • qm snapshot Command Examples in Linux

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright