Py学习  »  docker

基于docker+gunicorn部署sanic项目

Python中文社区 • 6 年前 • 594 次点击  

编程狗
编程大牛技术分享平台

最近云服务提供商在打价格战,我在某云上花了很少的钱租了一个月的云服务器: 公网ip是: 116.85.42.182, 以下我以116.85.42.182这个ip为演示,当你自己在部署的时候请换乘自己的ip地址.

买完服务器之后,你会得到一个公网ip,你可以通过ssh命令连接上你的服务器.

  1. ssh dc2-user@116.85.42.182

顺便提一句,某云给你创建的账户叫"dc2-user",你需要自己设置root的密码.

然后安装docker:

  1. sudo apt-get install http://docker.io

演示一个最小的sanic-app,来部署一下. 这是项目树(目录).

  1. .

  2. ├── app.py

  3. ├── Dockerfile

  4. └── templates

  5.    └── index.html

  6. 1 directory, 3 files

app.py

  1. import os

  2. from sanic import Sanic

  3. from sanic.response import html

  4. from sanic.response import HTTPResponse

  5. from jinja2 import Environment, FileSystemLoader

  6. app = Sanic(__name__)

  7. base_dir = os.path.abspath(os.path.dirname( __file__))

  8. templates_dir = os.path.join(base_dir, 'templates')

  9. jinja_env = Environment(loader=FileSystemLoader(templates_dir), autoescape=True)

  10. def render_template(template_name: str, **context) -> str:

  11.    template = jinja_env.get_template(template_name)

  12.    return template.render(**context)

  13. @app.route('/')

  14. async def index(request) -> HTTPResponse:

  15.    return html(render_template('index.html'))

这里的python代码,用到了sanic框架和jinja2木板引擎,所以带会需要安装这两个依赖.

Dockerfile

  1. FROM taoliu/gunicorn3

  2. WORKDIR /code

  3. ADD . /code

  4. RUN pip install sanic \

  5.    && pip install jinja2

  6. EXPOSE 8080

  7. CMD gunicorn app:app --bind 0.0.0.0:8080 --worker-class sanic.worker.GunicornWorker

第一行那里"FROM taoliu/gunicorn3",由于没找到合适的Python3的gunicorn的基础镜像,所以我自己做了一个,方便所有人使用.

RUN pip install sanic \ && pip install jinja2 这里,来安装那两个依赖.

CMD gunicorn app:app --bind 0.0.0.0:8080 --worker-class sanic.worker.GunicornWorker 这行,是镜像运行他所以执行的命令.

templates/index.html

  1. lang="en">

  2.     charset="UTF-8">

  3.    ltoddy's home

  4.     rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.css">

  5. class="container">
  6.    

    class="page-header">
  7.        

    Welcome

  8.    

  • 然后把这些文件传到服务器上:

    1. scp -r * dc2-user@116.85.42.182:~

    然后ssh连上我们的服务器,去构建我们的docker镜像(这个过程有些漫长,具体看网速.)

    1. docker build -t sanic-demo .

    1. docker images

    来查看一下当前拥有的镜像

    然后后台运行docker镜像:

    1. docker run -d --restart=always -p 5000:8080 sanic-demo:latest

    这时候打开浏览器输入: 116.85.42.182:5000 来看看效果吧.

    最后说明一点,去某云那里的防火墙规则那里,添加5000端口的规则.

    作者Alice,The computer science actually has a lot in common with magic.

    最近热门文章

    如何用Python做一个骚气的程序员

    用Python爬取陈奕迅新歌《我们》10万条评论的新发现

    机器学习算法KNN简介及实现

    Python有趣的解包用法

    用Python分析苹果公司股价数据

    Nginx+uwsgi部署Django应用

    Python自然语言处理分析倚天屠龙记

    Python 3.6实现单博主微博文本、图片及热评爬取

    ▼ 点击下方阅读原文免费成为社区会员


    今天看啥 - 高品质阅读平台
    本文地址:http://www.jintiankansha.me/t/qCqhQ34TIi
    Python社区是高质量的Python/Django开发社区
    本文地址:http://www.python88.com/topic/10801
     
    594 次点击