海纳百川无所不容,Win10环境下使用Docker容器式部署前后端分离项目Django+Vue.js

刘悦的技术博客 2020-11-17 22:52:54
海纳百川 纳百川 百川 无所不容 无所


原文转载自「刘悦的技术博客」https://v3u.cn/a_id_179

随着现代化产品研发的不断推进,我们会发现,几乎每个产品线都会包含功能各异的服务,而且服务与服务之间存在也会存在着错综复杂的依赖和被依赖关系,这就会带来一个世界性难题,项目部署的时候需要运维来手动配制服务之间通信的协议和地址,稍有不慎就会导致服务异常,同时如果服务器因为坏道或者其他原因导致更换物理机,重新部署新环境的成本也会非常之高。因此,我们就会寄希望于Docker这种的容器技术可以让我们构建产品所需要的所有的服务能够迅速快捷的重新部署,并且可以根据需求做横向扩展,且能够保证稳定的容灾性,在出现问题的时候可以利用守护进程自动重启或者启动容灾备份。

本次我们将在Win10环境下利用Docker容器技术来对前后端分离项目Django+Vue.js进行打包,分别定制化对应的项目镜像,应对快速部署以及高扩展的需求。

首先当然是安装Docker,可以参照这篇视频攻略:win10安装配置Docker并更换国内源

随后在宿主机安装gunicorn,容器内我们用异步的方式来启动Django

pip3 isntall gunicorn gevent

Django项目配置settings.py对应的应用:

# 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项目的根目录编写gunicorn的配置文件:gunicorn.conf.py

import multiprocessing
bind = "0.0.0.0:8000" #绑定的ip与端口
workers = 1 #进程数

这里注意一点,ip必须是0.0.0.0,不要写成127.0.0.1,否则外部环境会访问不到容器内的服务,接下来在项目的根目录编写好依赖列表: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

这里需要注意的是,某些依赖的库最好用==标注出小版本,因为一会在容器内通过pip安装的时候,系统有可能会自动帮你安装最新版导致一些依赖报错。

下面就是老套路,在根目录编写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"]

本次的基础镜像我们选择3.7,毕竟2020年了,与时俱进还是很必要的。

ok,万事俱备,运行命令对项目进行打包:

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.

这里注意一点就是要进入到项目的目录下执行

docker build -t 'mydjango' .

这里我的项目目录是mydjango。

第一次打包编译的时候,可能时间会长一点,耐心等一会就可以了,如果中途遇到网络错误导致的失败,反复执行打包命令即可,此时运行命令:

docker images

可以看到编译好的镜像大概有1g左右:

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

随后启动镜像服务:

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

这里我们用端口映射技术将宿主机的5000端口映射到容器内的8000端口,访问Django服务,http://容器ip:5000

后端搞定,接下来轮到我们的前端服务vue.js了,首先打开vue项目的打包配置文件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
}
}

将打包目录改成相对路径,同时注意路由的配置,如果曾经修改为history模式记得改回hash:

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

准备工作完毕,在vue的项目根目录下编写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镜像。

随后进入项目的根目录,执行打包命令:

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.

系统会自动根据脚本进行安装依赖,第一次也需要等待一段时间。

打包完成后,执行:

docker images

可以看到前端镜像的体积要小一点:

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

运行前端服务:

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

同样使用端口映射,这次宿主机使用8081,当然了,如果需要可以根据喜好进行修改。

访问Vue.js服务,http://容器ip:8081

至此,通过Docker的容器技术,我们就将前后端两大服务都分别部署好了,过程并不复杂,但是意义却是里程碑式的,携此两大镜像,左牵Django,右擎Vue.js,如果哪天需要横向扩容,只需短短几分钟,我们就可以在新服务器上做到“拎包入住”,灵活方便。最后奉上项目文件,与君共勉:https://gitee.com/QiHanXiBei/... https://gitee.com/QiHanXiBei/myvue

原文转载自「刘悦的技术博客」 https://v3u.cn/a_id_179

版权声明
本文为[刘悦的技术博客]所创,转载请带上原文链接,感谢
https://segmentfault.com/a/1190000038204164

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database