简体   繁体   中英

How to expose ports only within the docker network?

I have a few apps running in a Docker network with their ports ( 3000 , 4200 , etc) exposed. I also have an nginx container running within the same Docker network which hosts these apps on port 80 with different domain names ( site1.com , site2.com ).

But right now if I go directly to the ports the apps are running on ( localhost:3000 ) I can access them that way too.

How do I expose those ports only to the nginx container and not the host system?

But right now if I go directly to the ports the apps are running on (localhost:3000) I can access them that way too.

Thats because you are using -p aka --publish command in your docker run

Explanation:

If you want to expose ports between containers only, Do Not use -p or --publish just put them on the same docker network.

Example:

Lets create a new user-defined network:

sudo docker network create appnet

Lets create nginx container for reverse proxy, It should be available to outside world so we use publish.

sudo docker run --name nginx -d --network appnet nginx

Now put your apps in the same network but do not expose ports.

sudo docker run --name app1 -d --network appnet <app image name/id>

You have to use Docker networks .

The default network is shared with host, thus accessible from localhost. You can either configure Docker, creating a network manually, or let tools like docker-compose or Kubernetes to do it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM