今天分享的第三个博客,分享一下我的前端的部署案例,我的前端是React写的,但是Dockerfile通用,大家直接拿过去用就可以,如果是docker不太会的话,只是想尝试部署,大家可以看我的docker-compose 教程:Docker Compose | 菜鸟教程
其实大家安装好docker-compose 之后直接 docker-compose up 就可以运行起来了
如果有代理的话,请在.env文件中添加proxy或者更改Dockerfile内容,没有请忽略
Dockerfile:
FROM node:16 as builder
WORKDIR /portal
COPY . .
ARG proxy=""
RUN if [ "$proxy" != "" ]; \
then npm config set proxy "$proxy" && npm config set https-proxy "$proxy"; \
else echo Do not set proxy; \
fi
RUN npm install
RUN chmod +x node_modules/.bin/tsc
RUN chmod +x node_modules/.bin/vite
RUN npm run build
FROM nginx:alpine
WORKDIR /portal
COPY --from=builder /portal/dist/ /usr/share/nginx/html/
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/nginx.conf
COPY default.conf.template /etc/nginx/conf.d
CMD /bin/sh -c "envsubst '80' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'
需要的文件 nginx.conf
error_log stderr;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
access_log /dev/stdout;
server_tokens off;
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf;
}
需要的文件 default.conf.template
server {
listen 80 default_server;
location ^~ / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location @router {
rewrite ^.*$ /index.html last; # important!
}
location ~* \.(?:manifest|appcache|html?|xml|json)$ {
root /usr/share/nginx/html;
if ($request_uri ~* .*[.](manifest|appcache|xml|json)$) {
add_header Cache-Control "public, max-age=2592000";
}
if ($request_filename ~* ^.*[.](html|htm)$) {
add_header Cache-Control "public, no-cache";
}
expires -1;
}
location ~* \.(?:js|css|map|jpg|png|svg|ico)$ {
root /usr/share/nginx/html;
try_files $uri =404;
expires 1y;
access_log off;
add_header Cache-Control "public";
}
location ~ ^.+\..+$ {
root /usr/share/nginx/html;
try_files $uri =404;
include /etc/nginx/mime.types;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
现在需要的文件都有了,大家就可以先编译镜像然后在启动了,启动时请用端口绑定,绑定主机****端口到docker 80,然后访问主机的****端口就行了
下面是我用docker-compose写的,可以参考下
version: "2"
services:
web:
platform: linux/amd64
container_name: node_web
build:
context: ./
dockerfile: Dockerfile
args:
- proxy=${proxy}
volumes:
- "./portal:/portal"
ports:
- ${portal_port}:80