nginx redirect http to https in docker container connection refused

Viewed 357

I have a working redirect from HTTP traffic to HTTPS traffic. The environment consists of a flask application in a docker container that is being routed through an NGINX docker container. Below is the nginx.conf file. After running docker-compose up I am able to get the containers active. After running curl localhost, I am getting a 301 Moved Permanently. However, when running curl https://localhost, I am getting a curl: (7) Failed to connect to localhost port 443: Connection refused. I checked my local computer network settings on macOS Big Sur, and the firewall is turned off (any traffic should be allowed in). I'm not sure what else I need to do to get this to work. I have also exposed the port 443 in the docker-compose file for the nginx container. Any advice would be helpful.

NGINX.conf

http {


upstream flask {
    server app:8000;
  }
  server {
    listen 80;
    server_name localhost;
    return 301 https://$server_name$request_uri;
  }

  server {
    listen 443 ssl;
    server_name localhost;

    ssl_certificate /etc/nginx/nginx/files/localhost.crt;
    ssl_certificate_key /etc/nginx/nginx/files/localhost.key;

    location / {
      proxy_pass http://flask;
      proxy_set_header Host "localhost";
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-Proto $scheme;
    }
  }
}

Docker Compose

version: "3"
services:
  app:
    container_name: app
    command: gunicorn --bind 0.0.0.0:8000 --workers 2 "app.server:app"
    volumes:
      - ./:/var/www
    build: app
    ports:
      - 8000:8000
    networks:
      MyNetwork:
        aliases:
          - flask

  nginx:
    container_name: nginx
    build: nginx
    volumes:
      - ./:/var/www
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
    ports:
      - 80:80
    expose:
      - "443"
    networks:
      - MyNetwork

networks:
  MyNetwork:
1 Answers

At first you should add port 443 to your docker-compose like this:

    ports:
      - 80:80
      - 443:443

Then you should volume /etc/nginx/nginx/files:

    volumes:
      - ./:/var/www
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/nginx/files:/etc/nginx/nginx/files
Related