Can I use multiple containers that have the same service on the same machine?

Hello Everyone.

I am new to docker and to docker compose.
I am trying to create new containers where each has multiple services in for portability.

For example consider the following compose file:

services:
  nextcloud-aio-mastercontainer:
    image: nextcloud/all-in-one:latest
    init: true
    restart: always
    container_name: nextcloud-aio-mastercontainer
    volumes:
      - nextcloud_aio_mastercontainer:/mnt/docker-aio-config
      - /var/run/docker.sock:/var/run/docker.sock:ro
    ports:
      - 8080:8080
    extra_hosts:
      - "host.docker.internal:host-gateway"
    environment:
      - APACHE_PORT=11000
      - APACHE_IP_BINDING=192.168.0.83
  nginx:
    container_name: nginx
    image: nginx:1.25.3
    restart: always
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./nginx:/etc/nginx
      - /etc/letsencrypt:/etc/letsencrypt
volumes:
  nextcloud_aio_mastercontainer:
    name: nextcloud_aio_mastercontainer

As you can see, it uses nginx service in which I provide the configuration files which has the server name cloud.example.com.
And when the docker container is running, when I visit https://cloud.example.com I expect to see the NextCloud default page.

On the same server, I am running another container which uses nginx service which uses the same ports but nginx uses a different server name 'files.example.com`. However if my previous container is running I get errors that my host port is already used.

I know that I cannot re-use ports that my host is already using and web servers by default use ports 80 and 443 and if I want to visit files.example.com I should add a different port to it. Meaning that in the docker container I need to map different ports like 8080:8080 and enter the url files.example.com:8080 if I want to visit that page.

I am wondering though if there is any way of directly visiting files.example.com without the port.

Yes, use a reverse proxy like Traefik, nginx, caddy or haproxy to route requests by domain to target services/containers.

There is nginx-proxy which can automatically route by environment variables on the target service/container. That’s easy to use.

Traefik can do Configuration Discovery via labels in Docker and Docker Swarm, it’s more advanced, also a bit more complex. See simple Traefik example.

Note that NextCloud AIO will usually not work with automatic detection, as the AIO container will spin up more containers by itself, to which you probably can’t add env vars or labels.