基于docker部署sanic项目

源代码: https://github.com/ltoddy/ltoddy.github.io/tree/master/app

我租的服务器公网ip是116.85.42.182,你自己部署的时候请换成自己的公网ip!!!

最近云服务提供商再打价格战,福利多多,前两天就在滴滴云上花了0.9元租了个服务器,还是SSD(超值)!

去租云服务,然后他会让你选择你要安装的系统,我用的是ubuntu16.04,因为ubuntu我还是比较熟悉的.

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

ssh [email protected]

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

然后安装docker:

sudo apt-get install docker.io

演示一个最小的sanic-demo,来部署一下.

.
├── app.py
├── Dockerfile
└── templates
    └── index.html

1 directory, 3 files

这是项目树.

app.py

import os
from sanic import Sanic
from sanic.response import html
from jinja2 import Environment, FileSystemLoader

base_dir = os.path.dirname(os.path.abspath(__name__))
templates_dir = os.path.join(base_dir, 'templates')
jinja_env = Environment(loader=FileSystemLoader(templates_dir), autoescape=True)
app = Sanic(__name__)


def render_template(template_name, **context):
    template = jinja_env.get_template(template_name)
    return template.render(context)


@app.route('/')
async def index(request):
    return html(render_template('index.html'))

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

Dockerfile

FROM taoliu/gunicorn3

WORKDIR /app

ADD . /app

RUN pip install sanic \
    && pip install jinja2

EXPOSE 8080

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 这行,是镜像运行他所以执行的命令, 解释一下 app:app, 我们要运行的那个python文件叫app.py,其中app.py中的那个应用叫app(app = Sanic(__name__)), 比如,你过去是python manage.py 这样运行项目,那这里就改成manage:app, manage.py 中的 if __name__ == ‘__main__’ 可以去掉了.

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>ltoddy's home</title>
  <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.css">
</head>
<body>
<div class="container">
  <div class="page-header">
    <h1>Welcome</h1>
  </div>
</div>
</body>
</html>

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

scp -r * [email protected]:~

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

docker build -t sanic-demo .
然后
docker images
来查看一下当前拥有的镜像 然后后台运行docker镜像:
docker run -d –restart=always -p 5000:8080 sanic-demo:latest

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

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

猜你喜欢

转载自blog.csdn.net/ltoddy/article/details/79858628