海納百川無(wú)所不容,Win10環(huán)境下使用Docker容器式部署前后端分離項(xiàng)目Django+Vue.js

原文轉(zhuǎn)載自「劉悅的技術(shù)博客」https://v3u.cn/a_id_179

隨著現(xiàn)代化產(chǎn)品研發(fā)的不斷推進(jìn),我們會(huì)發(fā)現(xiàn),幾乎每個(gè)產(chǎn)品線都會(huì)包含功能各異的服務(wù),而且服務(wù)與服務(wù)之間存在也會(huì)存在著錯(cuò)綜復(fù)雜的依賴和被依賴關(guān)系,這就會(huì)帶來(lái)一個(gè)世界性難題,項(xiàng)目部署的時(shí)候需要運(yùn)維來(lái)手動(dòng)配制服務(wù)之間通信的協(xié)議和地址,稍有不慎就會(huì)導(dǎo)致服務(wù)異常,同時(shí)如果服務(wù)器因?yàn)閴牡阑蛘咂渌驅(qū)е赂鼡Q物理機(jī),重新部署新環(huán)境的成本也會(huì)非常之高。因此,我們就會(huì)寄希望于Docker這種的容器技術(shù)可以讓我們構(gòu)建產(chǎn)品所需要的所有的服務(wù)能夠迅速快捷的重新部署,并且可以根據(jù)需求做橫向擴(kuò)展,且能夠保證穩(wěn)定的容災(zāi)性,在出現(xiàn)問(wèn)題的時(shí)候可以利用守護(hù)進(jìn)程自動(dòng)重啟或者啟動(dòng)容災(zāi)備份。

本次我們將在Win10環(huán)境下利用Docker容器技術(shù)來(lái)對(duì)前后端分離項(xiàng)目Django+Vue.js進(jìn)行打包,分別定制化對(duì)應(yīng)的項(xiàng)目鏡像,應(yīng)對(duì)快速部署以及高擴(kuò)展的需求。

首先當(dāng)然是安裝Docker,可以參照這篇視頻攻略:win10安裝配置Docker并更換國(guó)內(nèi)源

隨后在宿主機(jī)安裝gunicorn,容器內(nèi)我們用異步的方式來(lái)啟動(dòng)Django

pip3 isntall gunicorn gevent

Django項(xiàng)目配置settings.py對(duì)應(yīng)的應(yīng)用:

# Application definition  
  
INSTALLED_APPS = [  
    'django.contrib.admin',  
    'django.contrib.auth',  
    'django.contrib.contenttypes',  
    'django.contrib.sessions',  
    'django.contrib.messages',  
    'django.contrib.staticfiles',  
    'corsheaders',  
    'rest_framework',  
    'myapp',  
    'dwebsocket',  
    'gunicorn'  
]

然后在Django項(xiàng)目的根目錄編寫(xiě)gunicorn的配置文件:gunicorn.conf.py

import multiprocessing  
  
bind = "0.0.0.0:8000"   #綁定的ip與端口  
workers = 1                #進(jìn)程數(shù)

這里注意一點(diǎn),ip必須是0.0.0.0,不要寫(xiě)成127.0.0.1,否則外部環(huán)境會(huì)訪問(wèn)不到容器內(nèi)的服務(wù),接下來(lái)在項(xiàng)目的根目錄編寫(xiě)好依賴列表:requirements.txt

Django==2.0.4  
django-cors-headers==2.5.3  
djangorestframework==3.9.3  
celery==4.4.2  
dwebsocket==0.5.12  
redis==3.3.11  
pymongo==3.8.0  
PyMySQL  
Pillow  
pyjwt  
pycryptodome  
selenium  
qiniu  
gunicorn  
gevent

這里需要注意的是,某些依賴的庫(kù)最好用==標(biāo)注出小版本,因?yàn)橐粫?huì)在容器內(nèi)通過(guò)pip安裝的時(shí)候,系統(tǒng)有可能會(huì)自動(dòng)幫你安裝最新版導(dǎo)致一些依賴報(bào)錯(cuò)。

下面就是老套路,在根目錄編寫(xiě)DockerFile文件:

FROM python:3.7  
WORKDIR /Project/mydjango  
  
COPY requirements.txt ./  
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple  
  
COPY . .  
ENV LANG C.UTF-8  
  
CMD ["gunicorn", "mydjango.wsgi:application","-c","./gunicorn.conf.py"]

本次的基礎(chǔ)鏡像我們選擇3.7,畢竟2020年了,與時(shí)俱進(jìn)還是很必要的。

ok,萬(wàn)事俱備,運(yùn)行命令對(duì)項(xiàng)目進(jìn)行打包:

liuyue@DESKTOP-NVU6CCV MINGW32 ~/www/mydjango (master)  
$ docker build -t 'mydjango' .  
Sending build context to Docker daemon  17.57MB  
Step 1/7 : FROM python:3.7  
 ---> 5b86e11778a2  
Step 2/7 : WORKDIR /Project/mydjango  
 ---> Using cache  
 ---> 72ebab5770a2  
Step 3/7 : COPY requirements.txt ./  
 ---> Using cache  
 ---> b888452d1cad  
Step 4/7 : RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple  
 ---> Using cache  
 ---> a576113cff5a  
Step 5/7 : COPY . .  
 ---> 5c5247d5a743  
Step 6/7 : ENV LANG C.UTF-8  
 ---> Running in af84623622a6  
Removing intermediate container af84623622a6  
 ---> f3d876487dab  
Step 7/7 : CMD ["gunicorn", "mydjango.wsgi:application","-c","./gunicorn.conf.py"]  
 ---> Running in d9392807ae77  
Removing intermediate container d9392807ae77  
 ---> c3ffb74ae263  
Successfully built c3ffb74ae263  
Successfully tagged mydjango:latest  
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

這里注意一點(diǎn)就是要進(jìn)入到項(xiàng)目的目錄下執(zhí)行

docker build -t 'mydjango' .

這里我的項(xiàng)目目錄是mydjango。

第一次打包編譯的時(shí)候,可能時(shí)間會(huì)長(zhǎng)一點(diǎn),耐心等一會(huì)就可以了,如果中途遇到網(wǎng)絡(luò)錯(cuò)誤導(dǎo)致的失敗,反復(fù)執(zhí)行打包命令即可,此時(shí)運(yùn)行命令:

docker images

可以看到編譯好的鏡像大概有1g左右:

liuyue@DESKTOP-NVU6CCV MINGW32 ~  
$ docker images  
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE  
mydjango            latest              c3ffb74ae263        24 hours ago        1.04GB

隨后啟動(dòng)鏡像服務(wù):

docker run -it --rm -p 5000:8000 mydjango

這里我們用端口映射技術(shù)將宿主機(jī)的5000端口映射到容器內(nèi)的8000端口,訪問(wèn)Django服務(wù),http://容器ip:5000

image

后端搞定,接下來(lái)輪到我們的前端服務(wù)vue.js了,首先打開(kāi)vue項(xiàng)目的打包配置文件config/index.js:

build: {  
    // Template for index.html  
    index: path.resolve(__dirname, '../dist/index.html'),  
  
    // Paths  
    assetsRoot: path.resolve(__dirname, '../dist'),  
    assetsSubDirectory: 'static',  
    assetsPublicPath: './',  
  
    /**  
     * Source Maps  
     */  
  
    productionSourceMap: true,  
    // https://webpack.js.org/configuration/devtool/#production  
    devtool: '#source-map',  
  
    // Gzip off by default as many popular static hosts such as  
    // Surge or Netlify already gzip all static assets for you.  
    // Before setting to `true`, make sure to:  
    // npm install --save-dev compression-webpack-plugin  
    productionGzip: false,  
    productionGzipExtensions: ['js', 'css'],  
  
    // Run the build command with an extra argument to  
    // View the bundle analyzer report after build finishes:  
    // `npm run build --report`  
    // Set to `true` or `false` to always turn it on or off  
    bundleAnalyzerReport: process.env.npm_config_report  
  }  
}

將打包目錄改成相對(duì)路徑,同時(shí)注意路由的配置,如果曾經(jīng)修改為history模式記得改回hash:

export default new Router({  
  routes:routes,  
  //mode:'history'   /*hash*/  
})

準(zhǔn)備工作完畢,在vue的項(xiàng)目根目錄下編寫(xiě)Dockerfile:

FROM node:lts-alpine  
  
# install simple http server for serving static content  
RUN npm install -g http-server  
  
# make the 'app' folder the current working directory  
WORKDIR /app  
  
# copy both 'package.json' and 'package-lock.json' (if available)  
COPY package*.json ./  
  
# install project dependencies  
RUN npm install  
  
# copy project files and folders to the current working directory (i.e. 'app' folder)  
COPY . .  
  
# build app for production with minification  
RUN npm run build  
  
EXPOSE 8080  
CMD [ "http-server", "dist" ]

這里我們選擇體積更小的alpine鏡像。

隨后進(jìn)入項(xiàng)目的根目錄,執(zhí)行打包命令:

docker build -t myvue .

這里我的前端目錄是myvue

liuyue@DESKTOP-NVU6CCV MINGW32 ~/www/myvue (master)  
$ docker build -t myvue .  
Sending build context to Docker daemon  202.1MB  
Step 1/9 : FROM node:lts-alpine  
lts-alpine: Pulling from library/node  
cbdbe7a5bc2a: Pull complete  
4c504479294d: Pull complete  
1e557b93d557: Pull complete  
227291017118: Pull complete  
Digest: sha256:5a940b79d5655cc688cfb319bd4d0f18565bc732ae19fab6106daaa72aeb7a63  
Removing intermediate container 5317abe3649b  
 ---> 2ddb8a0e3225  
Successfully built 2ddb8a0e3225  
Successfully tagged myvue:latest  
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

系統(tǒng)會(huì)自動(dòng)根據(jù)腳本進(jìn)行安裝依賴,第一次也需要等待一段時(shí)間。

打包完成后,執(zhí)行:

docker images

可以看到前端鏡像的體積要小一點(diǎn):

liuyue@DESKTOP-NVU6CCV MINGW32 ~  
$ docker images  
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE  
myvue               latest              917d1c69f10f        23 hours ago        539MB

運(yùn)行前端服務(wù):

docker run -it --rm -p 8081:8080 myvue

同樣使用端口映射,這次宿主機(jī)使用8081,當(dāng)然了,如果需要可以根據(jù)喜好進(jìn)行修改。

訪問(wèn)Vue.js服務(wù),http://容器ip:8081

image

至此,通過(guò)Docker的容器技術(shù),我們就將前后端兩大服務(wù)都分別部署好了,過(guò)程并不復(fù)雜,但是意義卻是里程碑式的,攜此兩大鏡像,左牽Django,右擎Vue.js,如果哪天需要橫向擴(kuò)容,只需短短幾分鐘,我們就可以在新服務(wù)器上做到“拎包入住”,靈活方便。最后奉上項(xiàng)目文件,與君共勉:https://gitee.com/QiHanXiBei/mydjango https://gitee.com/QiHanXiBei/myvue

原文轉(zhuǎn)載自「劉悅的技術(shù)博客」 https://v3u.cn/a_id_179

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容