cmonsqpr
cmonsqpr

Reputation: 603

How to access a docker container behind a reverse proxy on it's public address from another container

I setup 2 Docker containers a and b that both expose HTTP services. They should be publicly accessbile through their virtual host names a.domain.com and b.domain.com. Furthermore a should be able to access b on it's public virtual host name, i.e. it should be able to access b on b.domain.com.

The setup of the 2 containers is done using a docker-compose v2 file

version: '2'
services:
  a:
    container_name: container-a
    build:
      context: ../
      dockerfile: Containers/A.Dockerfile
    ports:
      - 5001:80
    environment:
      VIRTUAL_HOST: a.domain.com
    depends_on:
      - b
    networks:
      - my-net

  b:
    container_name: container-b
    build:
      context: ../
      dockerfile: Containers/B.Dockerfile
    ports:
      - 5000:80
    environment:
      VIRTUAL_HOST: b.domain.com
    networks:
      - my-net

networks:
  my-net:
    driver: bridge

I setup the jwilder/nginx-proxy docker container to automatically create reverse proxy nginx configurations. My two containers a and b are connected through their user-defined bridge network but also attached to the default bridge network on which the nginx-proxy is running (docker network connect bridge container-(a|b))

The nginx configuration generated by the nginx-proxy looks quite fine.

upstream a.domain.com {
            # a
            server 172.17.0.14:80;
}
server {
    server_name a.domain.com;
    listen 80 ;
    access_log /var/log/nginx/access.log vhost;
    location / {
        proxy_pass http://a.domain.com;
    }
}        
upstream b.domain.com {
            # a
            server 172.17.0.15:80;
}
server {
    server_name b.domain.com;
    listen 80 ;
    access_log /var/log/nginx/access.log vhost;
    location / {
        proxy_pass http://b.domain.com;
    }
}

Both containers can be reached from my client machine through their public virtual host names. The problem is that my container A cannot reach container B on it's virtual host name b.domain.com. It can access it through container-b, this is not an option for me however. Any ideas or hints on what I'm doing wrong?

Upvotes: 1

Views: 2780

Answers (1)

cmonsqpr
cmonsqpr

Reputation: 603

The solution is to add an alias to container b, so that when container a tries to resolve b.domain.com won't be redirected to the host but will find container b directly.

Simply add an alias in the docker compose file for container b: instead of

networks:
  - my-net

add

networks:
  my-net:
    aliases:
      - b.domain.com

Upvotes: 3

Related Questions