從零實現Linux一鍵自動化部署.netCore+Vue+Nginx項目到Docker中


環境搭建

1.安裝Linux,這里我用的阿里雲服務器,CentOS7版本
2.進入Linux,安裝Docker,執行以下命令

sudo yum update  #更新一下yum包
sudo yum install -y yum-utils  #安裝 yum-utils,它提供了 yum-config-manager,可用來管理yum源
yum -y install docker-ce #安裝Docker
yum list installed | grep docker #查看是否成功安裝Docker

如果提示No package docker-ce available則執行

sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo #設置Docker的源

安裝完成之后,啟動docker

sudo systemctl start docker #啟動Docker
sudo systemctl enable docker #設置Docker自啟動
systemctl status docker #查看Docker狀態


3.安裝Compose

curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.5/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose #安裝Compose
sudo chmod +x /usr/local/bin/docker-compose #修改目錄可執行權限(不然后續docker-compose up命令會報錯)
docker-compose --version #查看docker compose版本

至此環境搭建完成

配置.netCore應用

1.在項目右鍵添加Docker支持

vs會自動創建Dockerfile文件,自動創建的Dockerfile他的默認端口是80和433,這里我們改成5000
注意:修改默認端口需要設置環境變量ENV ASPNETCORE_URLS http://+:5000 5000為自定義的端口,修改后的文件如下

FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim AS base
WORKDIR /app
ENV ASPNETCORE_URLS http://+:5000
EXPOSE 5000

FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["Api/Api.csproj", "Api/"]
COPY ["Api.IServices/Api.IServices.csproj", "Api.IServices/"]
COPY ["Model/Api.Model.csproj", "Model/"]
COPY ["Common/Api.Common.csproj", "Common/"]
COPY ["Api.Repository/Api.Repository.csproj", "Api.Repository/"]
COPY ["Api.IRepository/Api.IRepository.csproj", "Api.IRepository/"]
COPY ["Api.Services/Api.Services.csproj", "Api.Services/"]
RUN dotnet restore "Api/Api.csproj"
COPY . .
WORKDIR "/src/Api"
RUN dotnet build "Api.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Api.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Api.dll"]

注意在代碼中配置Vue項目的跨域地址。

#在appsettings.json中添加跨域配置
"Cors": "http://localhost:8080,http://101.200.46.255";

#在Startup.cs中配置如下代碼
var cors = Configuration["Cors"].Split(",");
services.AddCors(x => x.AddPolicy("cors", policy => policy.AllowCredentials().AllowAnyMethod().AllowAnyHeader().WithOrigins(cors)));
app.UseCors("cors");

配置Vue項目

1.在根目錄下創建Dockerfile文件,並填寫以下內容

FROM node:lts-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install -g cnpm --registry=https://registry.npm.taobao.org  #設置淘寶的npm源
RUN cnpm install
COPY . .
RUN npm run build

# production stage
FROM nginx:stable-alpine as production-stage
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=build-stage /app/dist /usr/share/nginx/html

EXPOSE 80 #這里我們設置為80端口
CMD ["nginx", "-g", "daemon off;"]

2.在根目錄下創建nginx.conf文件配置nginx

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/share/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;
    #    }
    #}
 
 
}

這里我沒有配置反向代理,只是作為運行Vue的服務器,在上面已經配置了Vue的跨域地址
注意修改項目地址為公網ip

配置Compose

在.netCore項目中右鍵,添加“容器業務流程協調程序支持”。會在解決方案目錄創建docker-compose項目


這里我們吧docker-compose.override.yml文件刪除
然后修改docker-compose.yml文件

version: '3.7'

services:
  app:
    build:
      context: .   #配置上下文為當前解決方案目錄
      dockerfile: ./Api/Dockerfile  #定位dockerfile文件
    ports:
      - "5000:5000" //配置docker端口映射
    environment:
      TZ: Asia/Shanghai 
  proxy:
    build:
      context: ../web  #配置vue項目的根目錄,這里根據自己的目錄結構修改
      dockerfile: Dockerfile
    ports:
      - "80:80"
    environment:
      TZ: Asia/Shanghai
    depends_on:
        - app  #這里依賴.netCore項目,讓.netCore項目先啟動。

至此,所有前置工作都已完成。

部署

1.將代碼上傳至Github或Gitee里,或者打個包發送到Linux里,這里我選擇上傳到Gitee
2.拉取代碼或解包
3.將終端的路徑定位到docker-compose.yml文件所在目錄
4.構建鏡像

docker-compose build #構建鏡像

這一步可能會很慢,因為要從微軟的鏡像源下載Sdk和runtime

這里我是已經構建過了(因為這里我使用的是.net5.0所以只能從官方下載,如果你用的其他版本,可以先用.netcore tools提前安裝好相關sdk和runtime)。

出現這個就代表構建完成了。
5.啟動運行

docker-compose up #啟動容器


這樣就啟動完成了。可以從外網訪問了。

一些問題

防火牆

如果Linux啟動了防火牆,請將相應的端口開放

systemctl status firewalld #查看防火牆狀態
systemctl start firewalld  #開啟防火牆
systemctl stop firewalld #關閉防火牆
service firewalld start  #開啟防火牆 
#若遇到無法開啟
#先用
systemctl unmask firewalld.service 
#然后
systemctl start firewalld.service
firewall-cmd --zone=public --list-ports #查看防火牆開放的端口
firewall-cmd --zone=public --add-port=80/tcp --permanent   # 開放80端口
firewall-cmd --reload #重啟防火牆
netstat -lnpt #查看監聽的端口

如果嫌麻煩可以永久關閉防火牆

sudo systemctl disable firewalld #永久關閉防火牆

雲服務器安全規則

這里我用的阿里雲服務器,需要設置安全規則來開放端口,否則還是無法訪問
在安全組規則中添加相應端口后,即可訪問。

如果還是不行,可以全部重啟一下。

Linux中文亂碼問題

我在startup.cs中添加了數據庫遷移和種子數據的相關代碼。在Linux中進行build時,報錯了。提示startup.cs 文件編譯失敗。我打開Startup后,發現里面的中文都已經亂碼了。
然后經過百度,發現startup在linux上顯示為ISO-8859格式。將startup修改為ut8格式后,一切正常。
注:只要startup的格式是這個,其他文件的格式是utf-8(withBOM),所以不用修改。

附上本項目的Git地址:https://gitee.com/wlmy1996/personal_website


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM