How to Setup Nginx | Docker Swarm

Simple and easy way do setup and deploy nginx webserver using docker swarm.

mkdir -p nginx/{nginx-conf,ssl} && cd nginx
nano docker-compose.yml
version: '3.7'

services:
  prod:
    image: nginx:stable-alpine
    volumes:
      - ./nginx-conf:/etc/nginx/conf.d # place for nginx *.conf files
      - ./ssl:/etc/nginx/ssl # place for ssl certs
      - /webapps:/webapps  # this is where I like to keep my webapps
    networks:
      - durbok-net
    deploy:
      placement:
        constraints:
          - node.role == manager
      replicas: 1
      restart_policy:
        condition: on-failure
    ports:
      - 80:80
      - 443:443

networks:
  durbok-net:
    external: true

volumes:
  nginx-conf:
docker stack deploy -c docker-compose.yml nginx

When adding some nginx *.conf files you can test the configuration file and reload nginx service with:

# Test
docker exec -it nginx_prod.1.yzg8p2shj10c1ai06b1f1dyam nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

# Reload
docker exec -it nginx_prod.1.yzg8p2shj10c1ai06b1f1dyam nginx -s reload

That's it. Done.