Pragmatism in the real world

Changing port maps in Docker Compose

When using Docker Compose, I often map the ports to local ones in the compose.yaml like this:

services:
  web:
    build:
      context: ./docker/web
    ports:
      - "8080:80"

Adding to the port map

If port 8080 is in use already on a developer’s machine, then we can add a new mapping using compose.override.yaml

services:
  web:
    build:
      context: ./docker/web
    ports:
      - "8081:80"

The compose.override.yaml file is merged with the compose.yaml file and the effective configuration is now:

services:
  web:
    build:
      context: ./docker/web
    ports:
      - "8080:80"
      - "8081:80"

Replacing the port map

If we want to replace the original mapping with our new one, then we need the !override keyword in our compose.override.yaml file like this:

services:
  web:
    build:
      context: ./docker/web
    ports: !override
      - "8081:80"

Now the original mapping to port 8080 is removed as our new ports definition overrides the original, rather than being merged with it and so the effective configuration is:

services:
  web:
    build:
      context: ./docker/web
    ports:
      - "8081:80"

Removing the port map

If we want to remove the port mapping completely, we use !reset in our compose.override.yaml file:

services:
  web:
    build:
      context: ./docker/web
    ports: !reset []

Now, the ports property is completely removed, so the effective configuration is now:

services:
  web:
    build:
      context: ./docker/web

Note that you’d use !reset null, if you are removing a scalar, such as an environment variable.

Fin

The !override and !reset attributes work for any Compose property and while I’m sure they’ve been available for years, I’ve only just found out about them!

Another thing I recently learned is that docker-compose.yaml is only supported for backwards compatibility and the Docker Compose configuration file name is now compose.yaml.

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *