How to Expose Your Docker Ports Only to the Local Network

I’m currently in the process of breaking a monolith application into microservices that run in Docker containers. To keep things simple, the Docker containers are going to run on the same server as the monolith – at least, for the time being.

I wanted my containers to be able to communicate with each other as well as with the monolith, but to be otherwise inaccessible to the Internet. This proved to be more difficult than anticipated as Docker doesn’t play nicely with iptables and firewalld.

However, I managed to find a straightforward solution: in your docker-compose.yml file, be sure to bind your ports to 127.0.0.1. In my case, no IP was set, and as such, the ports were instead bound to 0.0.0.0, which made them accessible to the Internet. By binding the ports to 127.0.0.1, they became inaccessible to the Internet, but otherwise still available to other containers as well as the monolith.

For instance, the following code:

1ports:
2  - 27017:27017

should become:

1ports:
2  - 127.0.0.1:27017:27017