How to expose a Docker container port to one specific Docker network only, when a container is connected to multiple networks?

From the Docker documentation:

  • --publish or -p flag. Publish a container's port(s) to the host.
  • --expose. Expose a port or a range of ports.
  • --link. Add link to another container. Is a legacy feature of Docker. It may eventually be removed.

I am using docker-compose with several networks. I do not want to publish any ports to the host, yet when I use expose, the port is then exposed to all the networks that container is connected to. It seems that after a lot of testing and reading I cannot figure out how to limit this to a specific network.

For example in this docker-compose file with where container1 joins the following three networks: internet, email and database.

           - internet
           - email
           - database

Now what if I have one specific port that I want to expose to ONLY the database network, so NOT to the host machine and also NOT to the email and internet networks in this example? If I would use ports: on container1 it is exposed to the host or I can bind it to a specific IP address of the host. *I also tried making a custom overlay network, giving the container a static IPv4 address and trying to set the ports in that format in ports: like - '', but that also did not work because I think the binding can only happen to a HOST IP address. If i use expose: on container1 the port will be exposed to all three networks: internet, email and database.

I am aware I can make custom firewall ruling but it annoys me that I cannot write such simple config in my docker-compose file. Also, maybe something like 80: (HOST_IP:HOST_PORT:CONTAINER_IP:CONTAINER_PORT) would make perfect sense here (did not test it).*

Am I missing something or is this really not possible in Docker and Docker-compose?

Source: Docker Questions