version: '3.1'

services:

  postgres:
    image: postgres:11
    container_name : postgres_n8n${USER_ID:-1}
    restart: always
    environment:
      - POSTGRES_USER=${POSTGRES_NON_ROOT_USER}
      - POSTGRES_PASSWORD=${POSTGRES_NON_ROOT_PASSWORD}
      - POSTGRES_DB=${POSTGRES_DB}
      - POSTGRES_HOST=${POSTGRES_HOST}
      - PGDATA=/data/postgres
    networks:
      - traefik-proxy
    volumes:
      - ./init-data.sh:/docker-entrypoint-initdb.d/init-data.sh
      - postgresdata:/data/postgres

  n8n:
    image: n8nio/n8n
    restart: always
    environment:
      - DB_TYPE=postgresdb
      - DB_POSTGRESDB_HOST=${POSTGRES_HOST}${USER_ID:-1}
      - DB_POSTGRESDB_PORT=5432
      - DB_POSTGRESDB_DATABASE=${POSTGRES_DB}
      - DB_POSTGRESDB_USER=${POSTGRES_NON_ROOT_USER}
      - DB_POSTGRESDB_PASSWORD=${POSTGRES_NON_ROOT_PASSWORD}
      - N8N_BASIC_AUTH_ACTIVE=true
      - N8N_BASIC_AUTH_USER
      - N8N_BASIC_AUTH_PASSWORD
      - EXECUTIONS_PROCESS=main
      - WEBHOOK_TUNNEL_URL=${N8N_WEBHOOK_TUNNEL_URL}
    logging:
      options:
        max-size: '12m'
        max-file: '5'
      driver: json-file
    labels:
      - traefik.enable=true
      - traefik.http.routers.n8n${USER_ID:-1}.rule=Host(`${URL_N8N}`)
      - traefik.http.routers.n8n${USER_ID:-1}.entrypoints=websecure
      - traefik.http.routers.n8n${USER_ID:-1}.tls=true
      - traefik.http.routers.n8n${USER_ID:-1}.tls.certresolver=lets-encrypt
      - traefik.http.services.n8n${USER_ID:-1}.loadbalancer.server.port=${PORT_N8N}
      - traefik.http.middlewares.testheader.headers.accessControlAllowMethods="GET, OPTIONS, PUT, POST, DELETE"
      - traefik.http.middlewares.testheader.headers.accessControlAllowOriginList="*"    
      - traefik.http.middlewares.testheader.headers.addVaryHeader=true
      - traefik.http.middlewares.testheader.headers.accessControlAllowOrigin="*"
      - traefik.http.middlewares.testheader.headers.accessControlAllowHeaders="Origin, Accept,Content-Type, X-Requested-With, X-CSRF-Token"  
    networks:
      - traefik-proxy
    links:
      - postgres
    volumes:
      - n8n:/home/node/.n8n
    # Wait 5 seconds to start n8n to make sure that PostgreSQL is ready
    # when n8n tries to connect to it
    command: /bin/sh -c "sleep 30; n8n start"

networks:
  traefik-proxy:
    external:
      name: ${NETWORK_TRAEFIK}

volumes:
  postgresdata:
    driver: local
    driver_opts:
      type: none
      device: ${VOLUME_POSTGRES}
      o: bind

  n8n:
    driver: local
    driver_opts:
      type: none
      device: ${VOLUME_N8N}
      o: bind

