Home > OS >  Redirect http to https nginx in docker container
Redirect http to https nginx in docker container

Time:12-17

I am trying to redirect all HTTP traffic to HTTPS using nginx in a docker container. I am building the NGINX container using docker-compose up. After I run docker-compose up, I am getting an error:

[emerg] 1#1: cannot load certificate "/etc/nginx/etc/nginx/nginx/files/localhost.crt": BIO_new_file() failed (SSL: error:02001002:system library:fopen:No such file or directory:fopen('/etc/nginx/etc/nginx/nginx/files/localhost.crt','r') error:2006D080:BIO routines:BIO_new_file:no such file)

Below is my nginx.conf

NGINX.conf

http {
  upstream flask {
    server app:8000;
  }
  server {
    listen 80;
    server_name localhost;
  }

  server {
    listen 443 ssl;
    server_name localhost;

    ssl_certificate etc/nginx/nginx/files/localhost.crt; // this is location of where my certificate is on my local machine
    ssl_certificate_key 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;
    }
  }
}

I don't know why I'm getting this error of "no such file". Below is the Dockerfile for the NGINX image I am building and using. Any help would be appreciated.

NGINX dockerfile

FROM nginx:1.19.2-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY /files/localhost.crt /etc/nginx/nginx/files/localhost.crt

CodePudding user response:

Something like this is what you are looking for.

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; // this is location of where my certificate is on my local machine
    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;
    }
  }
}

You'll also need to copy the key in.

  • Related