I would like to conditionally open a debug port on one of the services in our docker-compose.yml
file when we want to run the debugger.
services:
service-one:
ports:
- "3000:3000"
- "1234:1234" # debugger port - conditionally allow based on env var or cmd line
service- two:
...
service-three:
...
We are running all of these services but for service-one
we want to conditionally open 1234 if it’s debug mode.
Can that be done by passing a command line in docker-compose up
?
docker-compose up --env-file .env.debug
Or can we do it some other way like using build stages in our Dockerfile
and somehow targeting debugging vs non-debugging ?
2
Answers
You could achieve it using docker-compose profiles. Here’s an excerpt from compose documentation
Here the services frontend and phpmyadmin are assigned to the profiles frontend and debug respectively and as such are only started when their respective profiles are enabled.
Services without a profiles attribute will always be enabled, i.e. in this case running docker-compose up would only start backend and db.
Valid profile names follow the regex format of [a-zA-Z0-9][a-zA-Z0-9_.-]+.
Note
The core services of your application should not be assigned profiles so they will always be enabled and automatically started.
Enabling profiles
To enable a profile supply the –profile command-line option or use the COMPOSE_PROFILES environment variable:
$ docker-compose –profile debug up
$ COMPOSE_PROFILES=debug docker-compose up
The above command would both start your application with the debug profile enabled. Using the docker-compose.yml file above, this would start the services backend, db and phpmyadmin.
Reference: https://docs.docker.com/compose/profiles/
You could probably do this with multiple Compose files. You can have a normal
docker-compose.yml
that sets up the service as you’d normally run it:And then a second
docker-compose.debug.yml
that has only the settings specific to the debugger setup.Now if you run
(and you need both
-f
options, with everydocker-compose
command, while you’re using this setup) then it will take theimage:
from the first file, and combine theports:
andenvironment:
from both files. When you don’t need the debugger, remove the-f docker-compose.debug.yml
option and it will only use the settings from the base file.