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:

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

As you can see, it uses nginx service in which I provide the configuration files which has the server name
And when the docker container is running, when I visit 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 '`. 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 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 if I want to visit that page.

I am wondering though if there is any way of directly visiting 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.