Quick tip: Docker compose network with docker port binding

You get a new project and you open the docker-compose.yml. It is as usual, each service as a container like postgresql, redis etc. But you see something weird. They have the ports exposed on the default port of the service. For example it has 5432:5432 for postrgresql, which means it will try to bind and expose the postgresql container port to the native OS port. If you run this docker compose build, you may have some weird behavior of the application and you don't want to do that.

Ok, first of all, if you are writing docker-compose.yml files, don't do that. I understand that many developers prefer to have everything into containers and open/close them based on the project. But having the default port exposed, you are forcing to stop the service and especially in production that's not a good thing.

There are three ways to fix this. One (the ugly way) is to stop the native service and run only the container as I mentioned before. But sometimes this cannot be done.

The second way (a bit less ugly) is to change the default port to something else. This means that you have to find every mention of the port inside the docker files and the project. It can be tedious and if for any reason you won't change it you may get strange results. For changing the HOST port, you need to change the first part. So for example at 8000:5432, the 8000 port is the Host port and 5432 is the container port.

Third way is to just keep the port private inside the network of this docker-compose. For doing this you replace 5432:5432 with 5432. Now it will be available only between the containers of the docker-compose. If you need to access this container you have to connect to the container or run some command from inside of this container (or connect somehow to the internal network). Additional information regarding docker network.

Have you ever had this problem before or something similar? Feel free to reach out and share your experience.
Max one mail per week.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.