• 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 backup and restore Docker containers
  2. “while” Loop Examples in Shell Scripts
  3. How to List / Search / Pull docker images on Linux
  4. How to Create a Public/Private Repository in Docker Hub and connect it remotely using command line
  5. How to write multiple plays and per-play privilege escalation in Ansible
  6. How to install Docker on Mac
  7. How to Map Static IP to your Domain (with GoDaddy example)
  8. How to Write Ansible Playbook and run it using the ansible-playbook command
  9. Strings and Variables in Python
  10. How to check the status and space used by images and containers

You May Also Like

Primary Sidebar

Recent Posts

  • vgextend Command Examples in Linux
  • setpci command – configure PCI device
  • db_load command – generate db database
  • bsdtar command – Read and write tape archive files

© 2022 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright