Home > Mobile >  Custom /etc/hosts file in Dockerfile
Custom /etc/hosts file in Dockerfile

Time:10-11

I am working on a project where /etc/hosts file with an additional entry must exist during container build, however the problems are as follows:

  1. During the build there is no hosts file at all.
  2. During the build everything is in read-only mode and I can't create the hosts file.
  3. In docker I even mounted an existing hosts file, but when I build, ITS STILL DOESNT EXISTS!

Everywhere written about extra_hosts, but these entries are added when the container is upped, they are not present during the build.

What is the solution to this problem? I need /etc/hosts existence.

Dockerfile

It used to work like this, but on my machine this line of the dockerfile returns an "read-only" error.

Docker Compose version 2.11.2, Docker version 20.10.18

CodePudding user response:

You can add an extra host during build:

docker build --help | grep host
      --add-host list           Add a custom host-to-IP mapping (host:ip)

This will create /etc/hosts and add the entries you need.

Docker-compose also supports this as of schema version 3.9. You can see the ful documentation here.

version: '3.9'

services:
  test:
    build:
      context: .
      extra_hosts:
      - "somehost:162.242.195.82"
      - "otherhost:50.31.209.229"
  • Related