nginx 如何让digitalocean droplet上的docker镜像具有https?

2g32fytz  于 2023-08-03  发布在  Nginx
关注(0)|答案(1)|浏览(113)

我有一个用python写的REST API,我已经dockerized了。我使用nextJS的前端,这要求我的API调用是https的网址(我想https反正)。我已经有了一个域的水滴设置,我已经让我的API在没有https的情况下工作。从我所读到的,我需要纳入nginx,以获得https。我可以让我的域名指向nginx或我的API。我如何设置它,以便我的REST API以某种方式合并nginx,以便我可以获得https?

pbpqsu0x

pbpqsu0x1#

所以你有你的docker容器,你的REST API运行在一个端口上,这个端口暴露在容器之外,我以8000为例,rest_api为docker容器名。
因为你已经在使用docker了,我建议你也用docker来设置nginx。首先,您需要为容器创建一个内部网络来进行通信。docker network create web应该做这个工作。然后你需要一个类似于下面的docker-compose.yml来设置nginx:

version: '3'

services:
  nginx:
    image: nginx:stable
    container_name: nginx
    restart: always
    volumes:
      - ./logs:/var/log/nginx # folder to write logs in
      - ./sites-enabled:/etc/nginx/conf.d:ro # all enabled sites .conf files
      - ./certbot/conf:/etc/letsencrypt:ro # configuration files by certbot (keys)
      - ./certbot/www:/var/www/certbot:ro # webroot for certbot check
    ports: # open ports on host
      - 80:80
      - 443:443
    networks: # attach container to an internal network
      - web

networks:
  web:
    external: true # web network gets declared outside of this file and should not be created with docker compose up

字符串
现在,您需要启动rest_api容器。重要的是,你也要将容器添加到Web网络中,这样它就可以被nginx容器找到。将端口暴露给内部网络而不是主机也很重要。例如docker-compose.yml文件:

version: '3'

services:
  rest_api:
    image: myimage
    container_name: rest_api
    expose: # expose only exposes the port to internal networks, ports would expose the ports to the host
      - 8000 # exposes port 8000 to internal connected networks
    networks:
      - web

networks:
  web:
    external: true


然后你只需要配置你的nginx设置。因此,您在sites-enabled目录中创建了一个mysite.conf文件。该文件可能看起来像下面这样:

server {
  listen 80;
  server_name mydomain.com;   # your domain name

  location / {
    proxy_pass http://rest_api:8000;   # needs to be http://<container_name>:<port_number>
    proxy_set_header   Host $host;   # all headers are optional, but help the applications getting information about the original request
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Host $server_name;
    proxy_set_header   X-Forwarded-Proto $scheme;
  }

  location ~ /.well-known/acme-challenge/ {   # this part would be for certbot certificate requests
    root /var/www/certbot;
  }
}


这是快速但详细的演练。让我知道如果它帮助或你有更多的问题。

相关问题