Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix read-only error when adding host in Docker? [duplicate]

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.

like image 613
sanz Avatar asked Mar 16 '26 09:03

sanz


1 Answers

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.

like image 112
Hitobat Avatar answered Mar 18 '26 05:03

Hitobat