1、准备一个测试的前端包
这里使用dist
2、编写nginx.conf.template
BACKEND_URL
是一个环境变量,从外部传入
user nginx;
worker_processes 1;
error_log logs/error.log error;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format combined '$remote_addr - $remote_user [$time_local] '
# '"$request" $status $body_bytes_sent '
# '"$http_referer" "$http_user_agent"';
#access_log access.log combined;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location /dist {
root /;
index index.html;
}
location /phm/ {
proxy_pass ${BACKEND_URL}/phm/;
}
location /phm/webSocketServer/ {
proxy_pass ${BACKEND_URL}/phm/webSocketServer/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
3、编写Dockerfile
FROM nginx:latest
RUN mkdir /dist
RUN mkdir -p /etc/nginx/logs
COPY ./dist /dist
COPY ./nginx.conf.template /
ENV BACKEND_URL=""
CMD envsubst '$BACKEND_URL' < /nginx.conf.template > /etc/nginx/nginx.conf \
&& cat /etc/nginx/nginx.conf \
&& nginx -g 'daemon off;'
4、打镜像并推送
docker build -t 192.168.100.91:80/phm-frontend:0.1.1 .
docker push 192.168.100.91:80/phm-frontend:0.1.1
5、测试运行
docker run -d -e BACKEND_URL=http://192.168.100.88:3201 -p 32280:80 192.168.100.91:80/phm-frontend:0.1.1
6、将前端的配置文件的配置通过环境变量传入,nginx不使用反向代理
param.js
var remoteUrl = 'http://${BACKEND_URL}'
var webSocketUrl = 'http://${BACKEND_URL}/phm/webSocketServer'
nginx.conf.template
user nginx;
worker_processes 1;
error_log logs/error.log error;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format combined '$remote_addr - $remote_user [$time_local] '
# '"$request" $status $body_bytes_sent '
# '"$http_referer" "$http_user_agent"';
#access_log access.log combined;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location /dist {
root /;
index index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
Dockerfile:
FROM nginx:latest
RUN mkdir /dist
RUN mkdir -p /etc/nginx/logs
COPY ./dist /dist
COPY ./nginx.conf.template /
COPY ./param.js /
ENV BACKEND_URL=""
CMD envsubst < /nginx.conf.template > /etc/nginx/nginx.conf \
&& envsubst '$BACKEND_URL' < /param.js > /dist/static/param.js \
&& cat /etc/nginx/nginx.conf \
&& nginx -g 'daemon off;'