/etc/hosts entry linked to another container IP

i have 2 container, 1 for nginx and 1 for php-fpm. On host machine i have web application files. I have created some vhosts on nginx container (eg. a.localhost.sk, b.localhost.sk, …).

When i try to call curl (from my web application) to any vhost i got error (unresolved host). I need add new lines to /etc/hosts on my php container linked to nginx container IP.

NGINX_CONTAINER_IP a.localhost.sk
NGINX_CONTAINER_IP b.localhost.sk

It is possible to configure something like this in docker-compose file?

Good evening.

What do you see in the hosts file?

There’s something that looks like? host.docker.internal

If not, you need to put that entry in there. But the problem is that every time you start the container it gets a random ip.

To overcome this, you need to use a script that will determine which ip is assigned to the container and write it to the hosts file.


set -e

if ! ping -q -c1 $HOST_DOMAIN > /dev/null 2>&1
 HOST_IP=$(ip route | awk 'NR==1 {print $3}')
 # shellcheck disable=SC2039
  echo -e "$HOST_IP\t$HOST_DOMAIN" >> /etc/hosts

# first arg is `-f` or `--some-option`
if [ "${1#-}" != "$1" ]; then
set -- php-fpm "$@"
exec "$@"

Then use the Dockerfile to copy it into the container

FROM ****


 COPY ./path_to_file/entrypoint.sh /usr/local/bin/docker-php-entrypoint
 RUN chmod +x /usr/local/bin/docker-php-entrypoint

You will then be able to access it from the container

 docker compose run --rm container_name curl -I host.docker.internal:8000
> HTTP/1.1 200 OK
> Server: nginx
> Date: Fri, 08 Sep 2023 18:38:56 GMT
> Content-Type: text/html
> Content-Length: 1310
> Connection: keep-alive
> Accept-Ranges: bytes
> Last-Modified: Fri, 08 Sep 2023 18:38:56 GMT
> X-Content-Type-Options: nosniff
> X-Frame-Options: DENY
> X-Xss-Protection: 1; mode=block