背景:已经后端在docker上部署了服务
需求:在同一台主机部署前后端,使其能访问通
- 创建Docker网络
docker network create my_network
docker network connect my_network aihuiyi-front
docker network connect my_network aihuiyi
- 配置Nginx
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
# 提供前端服务的静态文件
root /usr/share/nginx/html; # 请根据实际前端路径调整
index index.html index.htm;
}
location /startSession {
# 代理到后端服务
proxy_pass http://aihuiyi:8080; # 使用后端容器名称和端口
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
- 前端目录下写Dockerfile
# 使用Nginx镜像
FROM nginx
# 删除默认的Nginx配置文件
RUN rm -rf /usr/share/nginx/html/*
# 复制打包的文件到Nginx的web根目录
COPY dist /usr/share/nginx/html
# 复制自定义的Nginx配置文件
COPY ./nginx.conf /etc/nginx/nginx.conf
# 复制自定义的Nginx配置文件(如果有的话)
# COPY nginx.conf /etc/nginx/nginx.conf
# 暴露Nginx的默认端口
EXPOSE 80
# 启动Nginx
CMD ["nginx", "-g", "daemon off;"]
4.运行前端容器(建立在后端容器已运行的情况下)
docker build -t aihuiyi-front:v0.1.0 .
docker stop aihuiyi-front
docker rm aihuiyi-front
docker run -d --name aihuiyi-front --network my_network -p 5174:80 aihuiyi-front:v0.1.0