Docker Compose - 限制对某个容器的服务访问,并禁止从外部docker访问

时间:2018-06-02 05:10:10

标签: docker docker-compose

我有四项服务service1, service2, service3, postgres。每个都通过一些端口暴露。我想要的是postgres服务只能从docker容器访问,而不能通过psql命令从VM访问(禁用从docker外部访问)。

这是我的docker-compose.local.yml

version: '3'
services:
  postgres:
    container_name: postgres
    image: registry.domain.com/postgres-multi:9.5
    restart: unless-stopped
    ports:
      - "5432:5432"
    environment:
      LC_ALL: C.UTF-8
      POSTGRES_USER: postgres
      POSTGRES_MULTIPLE_DATABASES: service1,service2,service3
    volumes:
      - postgres_data:/var/lib/postgresql/data/

  service1:
    container_name: service1
    build:
      context: ./service1
      args:
        environ: local
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - "8001:8000"
    depends_on:
      - postgres
    environment:
      DATABASE_URL: 'postgres://postgres/service1'
      DJANGO_MANAGEPY_MIGRATE: 'on'
      DJANGO_MANAGEPY_COLLECTSTATIC: 'on'
      DJANGO_LOADDATA: 'off'
      DOMAIN: '0.0.0.0'
    volumes:
      - ./service1/app:/home/service1/app/app

  service2:
    container_name: service2
    build:
      context: ./service2
      args:
        environ: local
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - "8002:8000"
    depends_on:
      - postgres
      - service1
    environment:
      DATABASE_URL: 'postgres://postgres/service2'
      DJANGO_MANAGEPY_MIGRATE: 'on'
      DJANGO_MANAGEPY_COLLECTSTATIC: 'on'
      DJANGO_LOADDATA: 'on'
      DOMAIN: '0.0.0.0'
    volumes:
      - ./service2/app:/home/service2/app/app

  service3:
    container_name: service3
    build:
      context: ./service3
      args:
        environ: local
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - "8003:8000"
    depends_on:
      - postgres
      - service1
    environment:
      DATABASE_URL: 'postgres://postgres/service3'
      DJANGO_MANAGEPY_MIGRATE: 'on'
      DJANGO_MANAGEPY_COLLECTSTATIC: 'on'
      DJANGO_LOADDATA: 'on'
      DOMAIN: '0.0.0.0'
    volumes:
      - ./service3/app:/home/service3/app/app

volumes:
  postgres_data: 

1 个答案:

答案 0 :(得分:1)

如果您不想公开Postgres,我建议删除您的端口映射:ports: - "5432:5432"。这是将主机端口5432映射到容器端口,这使得它可以从主机上的该端口外部使用。