6

I'm trying to add a host to /etc/hosts in a Docker image. I have the following line in my Dockerfile:

RUN echo 10.162.34.15 my-host-name >> /etc/hosts

When I run docker build, I get the following error:

#8 0.624 /bin/sh: 1: cannot create /etc/hosts: Read-only file system

I've found various old questions from prior versions of Docker where /etc/hosts was read-only, but nothing relevant to why this would be happening in a later version. I'm using Docker Desktop for Mac 3.3.3, Docker engine 20.10.6.

I'm aware of docker run --add-host and extra_hosts in docker-compose. I'm willing to use one of these instead, but I'd like to at least understand the source of this error.

sanz
  • 135
  • 2
  • 7
  • The fundamental networking setup hasn't changed, and you can't provide this file in your image. (It's better to avoid needing to change `/etc/hosts` at all if you can; set up a DNS server to provide host name to IP address mappings instead.) – David Maze Sep 13 '21 at 20:51

1 Answers1

2

From the docker docs page on /etc/hosts, they say docker itself may update the file.

Since Docker may live update the container’s /etc/hosts file, there may be situations when processes inside the container can end up reading an empty or incomplete /etc/hosts file. In most cases, retrying the read again should fix the problem.

So because docker may rewrite the file, any changes you make from inside the image/container would be lost. To prevent this, they don't let you change it at all, so you get the read-only FS error.

Hitobat
  • 2,847
  • 1
  • 16
  • 12
  • The solution is to add --add-host parameter when building the docker image. Example: `docker build -t yourtag --add-host=yourdomainname:10.X.X.X .` – Shubham Saroj Jun 06 '23 at 10:57