Home > Software design >  docker-compose expose same port as the service
docker-compose expose same port as the service

Time:09-06

I have a docker-compose.yml:

services:
  backend:
    build: 
      ./backend
    ports:
      - 8100:8100
    container_name: "backend"
    
  frontend:
    build: 
      ./frontend
    ports:
      - 4200:4200
    container_name: "frontend"
    depends_on:
      - backend

And i want to get rid of the ports part. I have .env files in the folders /backend and /frontend with the portnumber set in there (e.g PORT=8100). In the dockerfile i can just do Export ${PORT}. But since i cant read the .env from the docker-compose location i am not able to expose the port in the same way. Is it possible to just have a wildcard to expose the port of the containers to the same port on my host like:

ports:
  - *:*

CodePudding user response:

No, there's no syntax like this. The ports: syntax always requires you to specify the container-side port, and you must have a ports: block if you want the container to be accessible from outside Docker.

If you weren't using Compose there is a docker run -P (capital P) option, but there the container ports are published on randomly-selected host ports. (This is one of the few contexts where "expose" as a Docker verb does anything useful: docker run -P publishes all exposed ports.)

However: there is no rule that the two port numbers must match. Rather than having the port number configurable in the Dockerfile (requiring a rebuild on any change) it's more common to use a fixed port number in the image and allow the host port number to be configured at deploy time.

For example, assume both images are configured to use the default Express port 3000. You can remap these when you run the containers:

version: '3.8'
services:
  backend:
    build: ./backend
    ports: ['8100:3000']
  frontend:
    build: ./frontend
    depends_on: [backend]
    ports: ['4200:3000']
  • Related