Skip to content

15、Docker构建前端镜像并运行

1、前端Dockerfile

dockerfile
# 基础镜像
FROM registry.cn-hangzhou.aliyuncs.com/xx_blog/nginx:1.27.2

# author
MAINTAINER maintainer="xx@qq.com"

# 复制html文件到路径
COPY dist/ /usr/share/nginx/html

EXPOSE 80

2、上传打包后的文件到服务器

bash
[root@xx-blog xx-spring-boot-web]# pwd
/root/xx-spring-boot-web
[root@xx-blog xx-spring-boot-web]# ls
dist  Dockerfile
[root@xx-blog xx-spring-boot-web]#

3、构建镜像

bash
docker build -t xx-spring-boot-web:v1 .

4、查看镜像

bash
[root@xx-blog xx-spring-boot-web]# docker images
REPOSITORY           TAG       IMAGE ID       CREATED          SIZE
xx-spring-boot-web   v1        2155d2ca31fa   4 seconds ago    192MB
xx-springboot        v1        82132e652235   44 minutes ago   546MB

5、运行

bash
docker run -d --name=xx-springboot-web -p 80:80 xx-spring-boot-web:v1

6.更改Dockerfile - 构建Docker镜像 - 运行Docker容器

  • Dockerfile
dockerfile
# 基础镜像
FROM registry.cn-hangzhou.aliyuncs.com/xx_blog/nginx:1.27.2

# author
LABEL maintainer="wisdom.su@163.com"

# 删除默认文件
RUN rm -rf /usr/share/nginx/html/*

# 复制配置文件到路径 Nginx 默认配置文件路径
COPY laosu.xin_80.config /etc/nginx/conf.d/

# 工作目录
WORKDIR /usr/share/nginx/html

# 复制html文件到路径
COPY dist/ .

# 设置文件权限(可选)
RUN chmod -R 755 /usr/share/nginx/html

# 端口
EXPOSE 80
  • laosu.xin_80.config
config
server {
  	listen 80;
	listen [::]:80;
	server_name laosu.xin;
	#server_name _;
	root /usr/share/nginx/html;
	index index.html index.htm;
	gzip on;
	gzip_min_length 1k;
	gzip_buffers 4 32k;
	gzip_comp_level 6;
	gzip_types text/plain applictation/x-javascript application/javascript text/javascript;
	gzip_vary on;
	gzip_disable "MSIE [1-6]\.";
	location / {
		try_files $uri $uri/ /index.html; # 支持vue的history模式
	}
	location ~ .*\.(gif|jpg|jpeg|txt|png|bmp|swf|mp3|ttf)$
	{
		expires	30d;
	}
	location ~ .*\.(js|css)?$
	{
		expires 12h;
	}

	error_page 500 502 503 504 /50x.html;
	location = /50x.html {
		root /usr/share/nginx/html;
	}

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/laosu.xin/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/laosu.xin/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

1. 上传DockerFile、laosu.xin_80.config、dist到服务器

2. 构建镜像

bash
docker build -t vue-app:latest .

3. 运行容器

bash

# 停止容器
docker stop vue-app

# 删除容器
docker rm vue-app

# 运行容器
docker run -d --name vue-app -p 8088:80 vue-app:latest
# -d 后台运行
# --name 指定容器名称
# -p 8088:80 指定端口映射 宿主机的8088端口映射到容器的80端口
# vue-app:latest 指定镜像名称和版本

# 查看容器 容器状态为UP
docker ps

4. 进入容器检查文件

bash
docker exec -it vue-app cat /etc/nginx/conf.d/default.conf

5. 测试访问

bash
curl http://localhost:8088