如何使用 Docker 构建一个代理服务器

演示如何使用 Docker 构建一个代理服务器,将请求代理到 https://api.openai.com/ 并使用 HTTPS 进行通信。

  • 在与 Dockerfile 相同的目录中创建一个名为 nginx.conf 的文件,并将以下内容复制到文件中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
events {
worker_connections 1024;
}

http {
server {
listen 443 ssl;
ssl_certificate /etc/nginx/cert.pem;
ssl_certificate_key /etc/nginx/cert.key;
ssl_session_cache shared:le_nginx_SSL:1m;
ssl_session_timeout 1440m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-128-CCM-8-SHA256:TLS13-AES-128-CCM-SHA256:EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+ECDSA+AES128:EECDH+aRSA+AES128:RSA+AES128:EECDH+ECDSA+AES256:EECDH+aRSA+AES256:RSA+AES256:EECDH+ECDSA+3DES:EECDH+aRSA+3DES:RSA+3DES:!MD5;

location / {
proxy_pass https://api.openai.com/;
proxy_ssl_server_name on;
proxy_set_header Host api.openai.com;
proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;
proxy_buffering off;
proxy_cache off;
}
}
}

请确保将 cert.pemcert.key 替换为您自己的 SSL 证书文件路径。

  • 在与 Dockerfile 相同的目录中,将您的 SSL 证书文件(包括 cert.pemcert.key)放置在该目录下。

  • 创建一个名为 Dockerfile 的文件,并将以下内容复制到文件中:

1
2
3
4
5
6
7
FROM nginx:latest

COPY nginx.conf /etc/nginx/nginx.conf
COPY cert.pem /etc/nginx/cert.pem
COPY cert.key /etc/nginx/cert.key

EXPOSE 443
  • 打开终端,切换到包含 Dockerfilenginx.conf 文件的目录。

  • 运行以下命令来构建 Docker 镜像:

1
docker build -t openai-proxy .
  • 构建完成后,运行以下命令来启动代理服务器容器:
1
docker run -d -p 8443:443 openai-proxy

这将在后台启动一个名为 openai-proxy 的容器,并将容器内的 443 端口映射到主机的 8443 端口。

现在,您可以通过访问 https://localhost:8443 来访问代理服务器,并通过代理服务器访问 https://api.openai.com/。请注意,这只是一个简单的示例,您可能需要根据需要进行更改和调整,以满足您的具体需求和环境配置。同时,使用自签名证书时,您的浏览器可能会显示安全警告,因为证书不是由受信任的颁发机构签发。