一、vue项目
1. 打包:
npm run build
# 也可以指定配置文件
npm run build:prod
打包后会在根目录的dist文件夹下生成静态资源,dist文件夹可通过修改配置修改为别的文件夹
2. 新建nginx.conf:
server {
listen 9000;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root /usr/share/nginx/html/;
index index.html index.htm;
try_files $uri $uri/ /index.html;
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept' always;
}
location /api {
proxy_pass http://192.168.31.136:9001;
proxy_set_header Host $host:$server_port;
}
location /auth {
proxy_pass http://192.168.31.136:9001;
proxy_set_header Host $host:$server_port;
}
}
- 设置前端服务的端口
- location - root 下设置静态资源的地址,即dist文件下的内容,由于我在后面将这些文件复制到了
/usr/share/nginx/html/
下,所以这样写 - 下面两个location我配置里代理,也就是说所有
/api
的请求都会交由http://192.168.31.136:9001
处理,这里通常配置的是后端接口的地址。
3. 新建Dockerfile:
# 设置基础镜像
FROM nginx:1.15
# 将dist文件中的内容复制到 /usr/share/nginx/html/ 这个目录下面
COPY dist/ /usr/share/nginx/html/
COPY nginx.conf /etc/nginx/conf.d/nginx.conf
EXPOSE 9000
- vue打包后的文件是通过nginx部署的,所以镜像基于nginx
- 将需要的资源文件及配置文件复制到容器中
- 暴露容器的9000端口
4. 上传项目到服务器:
本地打包的话实际上只上传dist文件夹即可。还有一种做法是只上传代码文件,在服务器完成打包,配上自动化部署一劳永逸,我这里先搞个简单的。上传之后是这样的,他们都在我创建的front文件夹下。
二、springboot项目
1. 打包:
mvn clean install
打包之后会在target文件夹下生成jar包
2. 新建Dockerfile:
FROM openjdk:8-jdk-alpine
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone && mkdir -p /event
WORKDIR /event
EXPOSE 9001
ADD ./target/event-api-0.0.1-SNAPSHOT.jar ./
CMD java -Djava.security.egd=file:/dev/./urandom -jar event-api-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
- 镜像基于jdk1.8
- 由于我在springboot的配置文件中配置的启动端口是9001,所以我暴露9001端口
- 将jar文件复制到容器中
- 运行jar文件启动springboot,并设置生效的配置文件为生产环境下的
3. 上传项目到服务器
同样的道理,可以本地打包上传,也可以上传代码在服务器打包,我是在本地打的包。上传之后是这样的,他们都在我创建的api文件夹下。
三、使用docker-compose进行容器编排
以上两步各会构建一个容器,我们这里使用docker-compose对两个容器进行统一管理。新建docker-compose.yml文件,这个时候文件夹是这样的,他们都在我创建的event目录下:
1. docker-compose.yml:
version: "3"
services:
front:
build: ./front
restart: always
ports:
- 9000:9000
container_name: event_front_c
depends_on:
- api
api:
build: ./api
restart: always
ports:
- 9001:9001
container_name: event_api_c
- front是我的vue项目,指定构建的文件夹是
./front
,这样会使用该目录下的dockerfile文件构建镜像 - restart设置容器自启动
- ports设置将宿主机的9000端口映射到容器的9000端口
- depends_on表示该容器的启动依赖于api容器,从而决定启动顺序
- api是我的springboot项目,配置同理
2. 启动容器:
docker-compose up --build -d
构建过程:
查看运行状态:
此时可以通过9000端口访问我的vue服务,并正常调用springboot接口