准備前端文件目錄
使用 npm run build 命令將vue項目打包,生成dist目錄。

將文件夾放到服務器上,我們這里是放到了服務器的 /usr/local 目錄下

編寫構建腳本
1.在當前目錄新建Dockfile文件
Dockerfile
# 指定基礎鏡像,必須為第一個命令 # 可以使用鏡像ID或者鏡像名稱 例如 nginx:1.14 FROM bb52fc3d3709 # 維護者信息 MAINTAINER su # 將本地文件添加到容器中 # 將dist文件中的內容復制到 /usr/local/nginx/html/ 這個目錄下面,該路徑是nginx容器生成的一個虛擬路徑,你的項目會存在這里。 COPY dist/ /usr/local/nginx/html/ COPY nginx.conf /etc/nginx/nginx.conf # 構建鏡像時執行的命令 RUN echo 'echo init ok!!'
注:如果指定的基礎鏡像沒有找到的話,會自動從倉庫中pull對應的鏡像。這里還有一種情況,如果是內網情況並且鏡像倉庫中沒有所需要的鏡像。可以在有這個鏡像的服務器上先導出鏡像,然后再復制到當前服務器進行導入即可。
# nginx.tar是導出tar包的文件名, # nginx:1.14是倉庫中的鏡像名稱,這里也可以直接使用鏡像ID # 導出鏡像 docker save -o nginx.tar nginx:1.14 # 導入鏡像,nginx.tar就是剛才導出的包 docker load -i nginx.tar
2.在當前目錄新建nginx配置文件 nginx.conf (注:nginx代理目錄就是剛才在Dockerfile文件中配置的虛擬目錄 /usr/local/nginx/html/ )
nginx.conf
worker_processes auto;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
client_max_body_size 20m;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root /usr/local/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
構建鏡像
命令(注意最后的 . 不可省略)
docker build -t test-vue:V1.0.0 .

5c238751e488就是構建完成后生成的鏡像ID
啟動鏡像
# run: 創建一個新的容器並運行一個命令 # -d: 后台運行容器,並返回容器ID # -p: 端口映射,格式為:主機(宿主)端口:容器端口 # --name="npmcs-test": 為容器指定一個名稱 docker run -p 8181:80 -d --name npmcs-test 5c238751e488
使用docker ps查看運行狀態,可以發現已經成功啟動該鏡像。

測試
訪問http://ip:8181進行測試
部署完畢后可以刪除 /usr/local/dist 目錄,不會影響鏡像的運行。
EOF
