10

Docker-compose's run reference includes the "--service-ports" flag.

 --service-ports       Run command with the service's ports enabled and mapped
                      to the host.

Source: https://docs.docker.com/compose/reference/run/

The description doesn't really tell me anything. Ports are mapped to the host on docker-compose up if I specify them in the docker-compose file. No matter if the flag is used or not.

What is it for?

1 Answer 1

7

According to the Docker documentation:

docker-compose run runs a one-time command against a service. [...]

Commands you use with run start in new containers with configuration defined by that of the service, including volumes, links, and other details. However, there are two important differences.

First, the command passed by run overrides the command defined in the service configuration. [...]

The second difference is that the docker-compose run command does not create any of the ports specified in the service configuration. This prevents port collisions with already-open ports. If you do want the service’s ports to be created and mapped to the host, specify the --service-ports flag:

docker-compose run --service-ports web python manage.py shell

Alternatively, manual port mapping can be specified with the --publish or -p options, just as when using docker run:

docker-compose run --publish 8080:80 -p 2022:22 -p 127.0.0.1:2021:21 web python manage.py shell

This is meant so that you can run singular commands against an already defined service or services using docker-compose run.

For example, lets say you set up a compose file that defines some kind of service. To start the service to run in the background you use docker-compose -f <FILE> up --detach but if you wanted to look inside the container using a terminal, you would run docker-compose run bash.

The reason for the ports being ignored is docker-compose run assumes the container is already set up, and has it's ports set up correctly. If you ran a script that did something involving ports using docker-compose run /path/to/script.sh you might not want it to change the ports that were correctly mapped with your docker-compose up command. This way, the option makes it so you have to tell docker explicitly "I actually want port mappings to change".

1
  • 1
    I see, that makes sense. Thank you for explaining!
    – Worp
    Mar 7, 2019 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.