1. 程式人生 > >基於docker部署sanic專案

基於docker部署sanic專案

我租的伺服器公網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埠的規則.