如何使容器仅对同一网络中的其他容器可见

How to make container visible only to other containers within the same network

我刚开始学习 docker 并尝试根据我的需要进行调整。 给定这样简单的 docker-compose file

version: '3'

services:

    my-client:
        container_name: my-client
        build:
            context: ./client
            dockerfile: Dockerfile_dev
        ports:
            - "3000:3000"
        volumes:
            - ./client/src:/srv/dev/client/src
            - ./client/public:/srv/dev/client/public
        command: npm run start

    my-nginx:
        container_name: my-nginx
        build: ./nginx
        links:
            - my-client
        expose:
            - 80
        ports:
            - "80:80"

(nginx只是代理请求给客户端)

目前我可以通过 localhostlocalhost:3000 访问我的客户端,这不太好。我只想在我的网络之外看到 1 个端口,并隐藏所有其他容器。是否有可能以 outside->nginx->client 而非 outside->client

的方式设置网络

只需放下这个:

ports:
            - "3000:3000"

那么访问这个容器的唯一方法是外部 -> nginx -> 客户端(或者 localhost,如果你尝试从容器 运行 所在的机器)。 Nginx 仍然可以到达 3000 端口的容器,但其他的则不能。