简体   繁体   中英

Docker environment, nginx reverse proxy, Local or global

Some docker-compose solutions, uses nginx as reverse proxy for security reasons, when exposing the service to the internet. Would it be more correct to install multiple docker services, with there own nginx (reverse proxy) or create one dedicated container, holding the nginx service, and redirect to all the "local" containers?

I'd almost always do this with only a single Nginx proxy, though more for simplicity than anything security-related.

An especially important pattern is around browser front-ends. Your React or Angular code runs in the browser, not in a container, so it can't use Docker networking; but for both deploy-time configuration and CORS reasons it's much better if the code and the back-end application are served from the same host and port. If you can use /api/whatever as the back-end URL, without embedding a host name or port, it will work anywhere the service can be deployed.

That would bring you a Compose setup like so:

version: '3.8'
services:
  ingress:
    image: nginx
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    ports:
      - '8888:80'  # <-- this is the only published port
  frontend:
    build: frontend
    # no ports:, volumes:, networks:, container_name:, _etc._
  backend:
    build: backend
    environment:
      - PGHOST=db
  db:
    image: postgresql
    environment: { ... }
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata:

In this stack, the only thing you can reach from outside Docker is the ingress container; nothing else has ports: . That's the (production) setup you want. (I tend to minimize differences between dev and prod Docker setups, but adding more ports: to e.g. directly access the database with psql and without docker exec is pretty helpful in non-prod.)

The Nginx configuration then has all of the URL routing you need

upstream backend { server backend:3000 }
upstream frontend { server frontend:3000 }

server {
  location / {
    proxy_pass http://frontend;
  }
  location /api {
    proxy_pass http://backend;
  }
}

You can do other things in this configuration like providing (unified) authentication checking, hiding .../admin/... routes, and integrate other services into your API. All of this is much harder to do consistently if you have many separate Nginxes.

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