Search code examples
dockerdocker-composeparameterization

How to parameterize ports for docker-compose?


I am trying to parameterize a docker-compose file using .env. Doc

docker-compose.yml

version: '2.3'
networks:
    default: { external: true, name: $NETWORK_NAME }
services:
    rabbitmq_local:
        image: 'rabbitmq:3.6-management-alpine'
        ports:
          # The standard AMQP protocol port
          - ${RABBIT_PORT}:5672
          # HTTP management UI
          - '15672:15672'

.env file

NETWORK_NAME=uv_atp_network
RABBIT_PORT=5672
RABBIT_HTTP_MANAGEMENT_PORT=15672

Parameterizing NETWORK_NAME works, but parameterizing RABBIT_PORT doesn't, with

The Compose file 'docker-compose.yml' is invalid because:
services.rabbitmq_local.ports contains an invalid type, it should be a number, or an object

This makes me suspect RABBIT_PORT is interpreted as string rather than a number.

How can I parameterize it correctly?


EDIT

I found that forcing the variable to be mandatory

- ${RABBIT_PORT:?unspecified_rabbit_port}:5672

gives the error, meaning it is unset or empty.

What am I doing wrong?


Solution

  • It seems that when running with pytest and pytest-docker-compose the .env file has to be in the root folder of pytest, along with the pytest.ini file.

    Running from docker-compose from command-line doesn't have that limitation in docker 1.24.

    After relocating the file, the variables could be resolved.