docker-compose warning on scale containers

Viewed 189

I've this docker-compose file:

version: "3.8"
services:

  web:
    image: apachephp:v1
    ports:
      - "80-85:80"
    volumes:
      - volume:/var/www/html
    network_mode: bridge

  ddbb:
    image: mariadb:v1
    ports:
      - "3306:3306"
    volumes:
      - volume2:/var/lib/mysql
    network_mode: bridge
    environment:
      - MYSQL_ROOT_PASSWORD=*********
      - MYSQL_DATABASE=*********
      - MYSQL_USER=*********
      - MYSQL_PASSWORD=*********

volumes:
  volume:
    name: volume-data
  volume2:
    name: volume2-data

When run this:

docker-compose up -d --scale web=2

Its works as well but receive this warning:

WARNING: The "web" service specifies a port on the host. If multiple containers for this service are created on a single host, the port will clash.

Can somebody help to avoid these warning?, thank you advance.

Best regards.

1 Answers

I suppose, you try to access the web service without knowing the port of the specific container and to distribute the requests to a container here. If i rigth, to do that, you need a load balancing mechanisms to the system configuration.In the following example, i'll use NGINX as the load balancer.

version: "3.8"
services:

  web:
    image: apachephp:v1
    expose: # change 'ports' to 'expose'
      - "7483" # <- this is web running port (Change to your web port) 
    ....

ddbb:
    ....
## New Start ##
nginx:
    image: nginx:latest
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - web # your web service name
    ports:
      - "80:80"
## New End ##
    
volumes:
  ...

So you don’t need to map the port 80-85:80 from the web services to a host machine port, if you want to scale the service. So i remove the port mapping configuration from your Docker Compose file and only expose the port as above:

In the nginx service and i add port mappings to the host container for that server. In example, i configured NGINX to listen on the port 4000, which is why we have to add port mappings for this port.

nginx.conf file contents:

user  nginx;

events {
    worker_connections   1000;
}
http {
        server {
              listen 4000;
              location / {
                proxy_pass http://pspdfkit:5000;
              }
        }
}

You will find here more details, to Use Docker Compose to Run Multiple Instances of a Service in Development.

Related