What to do when docker-compose run doesn't bind ports?

Docker is a great tool to create a self-contained environment to run your applications, dealing easily with the problems of package dependencies and other stuff that bothers every software developer.

However, generally, an application depends of other resources, like database, cache or even other applications.

To solve this problem, docker provides the docker-compose command, that handles all system dependencies.

Generally, to lift an entire environment, a simple docker-compose up is enough. However, sometimes, we want to run a specific command in a starting container.

For example:

Let’s suppose we have the following docker-compose.yml file:

Running…

docker-compose run api bash

… will start the environment described in docker-compose.yml, executing an interactive bash in the container labelled as api.

The problem comes when we do a port forward. By default, docker-compose run doesn’t forward its ports. It isn’t a bug, but its default behaviour, as described in Docker’s official documentation.

To overcome this behaviour, docker-compose run provides the –service-ports parameter, which enables port forwarding in docker-compose run.

So, our previous command becomes something like this:

docker-compose run --service-ports api bash

Now, all the required port forwarding described in docker-compose.yml will in fact be forwarded.

(PS: Thanks to Tiago Oliveira for helping me to figure it out)

Liked this post?

Have questions? Suggestions?

Follow me on Twitter and let's engage in a conversation