Dockerfile部署uwsgi+nginx+django(爭取做到很全)

背景

最近在和組內(nèi)小伙伴一起寫接口測試平臺后端,使用的是drf框架,目前已經(jīng)完成部分工作。在和前端聯(lián)調(diào)試另一個小伙伴使用uwsgi部署起來了撞秋,我感覺這樣部署很low,因為之前有了解過docker所以想著這一次徹底把docker給學(xué)會吧嚣鄙,于是就有了這篇文章吻贿。

首先先看一下我的目錄結(jié)構(gòu)

image.png

想法

我計劃使用兩個鏡像來部署我的項目,一個來部署django+uwsgi項目哑子,一個來運(yùn)行nginx舅列,兩個鏡像均使用Dockerfile。所以前提肯定是先把docker下載好卧蜓,再編寫好兩個鏡像帐要。

nginx文件

1. 編寫nginx的Dockerfile
FROM nginx

COPY nginx.conf /etc/nginx/nginx.conf

CMD ["nginx", "-g", "daemon off;"]
2. 編寫nginx.conf文件

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include  mime.types;
    
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       8080;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            uwsgi_pass maas:8001;
            include uwsgi_params;
        }
    location /static {
            alias /backend/static;
        
    }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    include servers/*;
}

Django項目所需文件

1. 編寫Dockerfile
FROM centos:7
MAINTAINER shd
RUN yum install -y gcc gcc-c++ make vie git libffi-devel \
openssl-devel pcre-devel gd-devel \
iproute net-tools telnet wget curl initscripts psmisc && \
yum clean all && \
rm -rf /var/cache/yum/*
COPY pythons/Python-3.8.2.tar.xz Python-3.8.2.tar.xz
RUN  tar -xvJf Python-3.8.2.tar.xz
RUN cd Python-3.8.2 && \
./configure prefix=/usr/local/python3 && \
make && make install && \
cd .. && rm -rf /Python-3.8.2* && \
    rm -rf /usr/bin/python && \
    ln -s /usr/local/python3/bin/python3 /usr/bin/python && \
    ln -s /usr/local/python3/bin/pip3 /usr/bin/pip
RUN set -ex \
    && sed -i "s#/usr/bin/python#/usr/bin/python2.7#" /usr/bin/yum \
    && sed -i "s#/usr/bin/python#/usr/bin/python2.7#" /usr/libexec/urlgrabber-ext-down \
    && yum install -y deltarpm \
    && pip install --upgrade pip

RUN pip install uwsgi && \
       ln -s /usr/local/python3/bin/uwsgi /usr/bin/uwsgi

COPY requirements.txt backend/requirements.txt
WORKDIR backend
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
EXPOSE 8001
EXPOSE 9191

#ENTRYPOINT ["/usr/bin/uwsgi", "uwsgi.ini"]
#CMD ["/bin/bash"]
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

ENTRYPOINT ["/entrypoint.sh"]

#CMD ["/usr/bin/uwsgi", "uwsgi.ini"]

2. entrypoint.sh
#!/bin/bash

uwsgi  uwsgi.ini
sleep 10000000  # 因為啟動容器后,總是會自動停止弥奸,因此先使用笨辦法讓容器sleep來避免容器停止榨惠,后續(xù)想辦法解決
3. uwsgi.ini
[uwsgi]
http= 0.0.0.0:8005
socket= :8001
chdir= /backend
wsgi-file= backend/wsgi.py
static-map= /static=/backend/static
master= 1
workers= 7
vacuum= true
uid= root
gid= root
pidfile= /backend/backend-uwsgi.pid
daemonize= /backend/uwsgi.log

構(gòu)造鏡像,啟動容器

1. 新創(chuàng)建一個網(wǎng)絡(luò)

??因為涉及到兩個容器盛霎,并且容器每次啟動后ip都會變赠橙,所以為了避免這種問題就需要自定義容器網(wǎng)絡(luò)。
容器一共有4種網(wǎng)絡(luò)模式愤炸,host期揪、none、container规个、bridge凤薛,默認(rèn)是bridge模式。因此我們自定義網(wǎng)絡(luò)也最好使用bridge模式诞仓,并且自定義的網(wǎng)絡(luò)可以解決容器啟動ip變更后缤苫,無法通信的問題。

(maas_backend_env) shd:maas_qa_backend shenhaodong$ docker network create --subnet=166.156.0.0/16 --gateway=166.156.0.1 shdnet 
e2f658e77a46f4a0140cf25cf6265ba12641b0fd6ced24a183379d14f455e1c6
(maas_backend_env) shd:maas_qa_backend shenhaodong$ docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
e8be82af8b3a   bridge    bridge    local
1274d320a029   host      host      local
c7c913872b2d   mynets    bridge    local
bd6d8d7b314c   none      null      local
e2f658e77a46   shdnet    bridge    local
(maas_backend_env) shd:maas_qa_backend shenhaodong$ 

2. 構(gòu)建項目鏡像并使用自定義網(wǎng)絡(luò)啟動

因為nginx容器依賴項目的鏡像狂芋,所以需要先啟動項目容器才可以去啟動nginx容器榨馁,具體可以參考nginx的配置文件,

  uwsgi_pass maas:8001; #容器名字+端口號
  • 構(gòu)建鏡像
(maas_backend_env) shd:maas_qa_backend shenhaodong$ docker build . -t centos:v1
[+] Building 1.8s (17/17) FINISHED                                                                                                                                                                                
 => [internal] load build definition from Dockerfile                                                                                                                                                         0.0s
 => => transferring dockerfile: 1.33kB                                                                                                                                                                       0.0s
 => [internal] load .dockerignore                                                                                                                                                                            0.0s
 => => transferring context: 2B                                                                                                                                                                              0.0s
 => [internal] load metadata for docker.io/library/centos:7                                                                                                                                                  1.2s
 => [internal] load build context                                                                                                                                                                            0.4s
 => => transferring context: 17.88MB                                                                                                                                                                         0.4s
 => [ 1/12] FROM docker.io/library/centos:7@sha256:0f4ec88e21daf75124b8a9e5ca03c37a5e937e0e108a255d890492430789b60e                                                                                          0.0s
 => CACHED [ 2/12] RUN yum install -y gcc gcc-c++ make vie git libffi-devel openssl-devel pcre-devel gd-devel iproute net-tools telnet wget curl initscripts psmisc && yum clean all && rm -rf /var/cache/y  0.0s
 => CACHED [ 3/12] COPY pythons/Python-3.8.2.tar.xz Python-3.8.2.tar.xz                                                                                                                                      0.0s
 => CACHED [ 4/12] RUN  tar -xvJf Python-3.8.2.tar.xz                                                                                                                                                        0.0s
 => CACHED [ 5/12] RUN cd Python-3.8.2 && ./configure prefix=/usr/local/python3 && make && make install && cd .. && rm -rf /Python-3.8.2* &&     rm -rf /usr/bin/python &&     ln -s /usr/local/python3/bin  0.0s
 => CACHED [ 6/12] RUN set -ex     && sed -i "s#/usr/bin/python#/usr/bin/python2.7#" /usr/bin/yum     && sed -i "s#/usr/bin/python#/usr/bin/python2.7#" /usr/libexec/urlgrabber-ext-down     && yum install  0.0s
 => CACHED [ 7/12] RUN pip install uwsgi &&     ln -s /usr/local/python3/bin/uwsgi /usr/bin/uwsgi                                                                                                            0.0s
 => CACHED [ 8/12] COPY requirements.txt maas_qa_backend/requirements.txt                                                                                                                                    0.0s
 => CACHED [ 9/12] WORKDIR maas_qa_backend                                                                                                                                                                   0.0s
 => CACHED [10/12] RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple                                                                                                           0.0s
 => CACHED [11/12] COPY entrypoint.sh /entrypoint.sh                                                                                                                                                         0.0s
 => CACHED [12/12] RUN chmod +x /entrypoint.sh                                                                                                                                                               0.0s
 => exporting to image                                                                                                                                                                                       0.0s
 => => exporting layers                                                                                                                                                                                      0.0s
 => => writing image sha256:34d6ab3660afcbef63792eb6b4a79f5ec8d30f65e7f79e04625ae22514a4cc74                                                                                                                 0.0s
 => => naming to docker.io/library/centos:v1 
  • 啟動容器帜矾,并且起名為maas
shd:maas_qa_backend shenhaodong$ docker run -itd -p 8008:8001 -p8006:8005 -v /Users/shenhaodong/PycharmProjects/maas_qa_backend:/backend --net shdnet --name maas 34d6ab3660af
dba395715a34ab4d8355687c1d83e81134b519e579ca3c86052957921121b3b2
(maas_backend_env) shd:maas_qa_backend shenhaodong$ docker ps 
CONTAINER ID   IMAGE          COMMAND            CREATED         STATUS         PORTS                                                      NAMES
dba395715a34   34d6ab3660af   "/entrypoint.sh"   4 seconds ago   Up 3 seconds   9191/tcp, 0.0.0.0:8008->8001/tcp, 0.0.0.0:8006->8005/tcp   maas


  • 通過telnet ip+port看看服務(wù)是否正常啟動
shd:maas_qa_backend shenhaodong$ telnet 127.0.0.1 8006
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.

#  可以看到在容器外可以訪問到服務(wù)的
3. 構(gòu)建nginx鏡像并使用自定義網(wǎng)絡(luò)啟動
  • 構(gòu)建鏡像
shd:nginx shenhaodong$ docker build . -t ngimages

[+] Building 9.3s (2/3)                                                                                                                                                                                           
 => [internal] load build definition from Dockerfile                                                                                                                                                         0.0s
 => => transferring dockerfile: 36B                                                                                                                                                                          0.0s
 => [internal] load .dockerignore                                                                                                                                                                            0.0s
 => => transferring context: 2B                                                                                                                                                                              0.0s
 => [internal] load metadata for docker.io/library/nginx:latest                                                                                                                                              9.2s
-

  • 啟動nginx容器
(maas_backend_env) shd:maas_qa_backend shenhaodong$ docker run -itd -p8009:8080 --name ng --net shdnet 3893b8f7aa8a
4e969d462c03a1d96e35b2a477abc4ee76285e3416ec6951a9f82b35029a7d4c
(maas_backend_env) shd:maas_qa_backend shenhaodong$ 
(maas_backend_env) shd:maas_qa_backend shenhaodong$ 
(maas_backend_env) shd:maas_qa_backend shenhaodong$ docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS         PORTS                                                      NAMES
4e969d462c03   3893b8f7aa8a   "/docker-entrypoint.…"   2 seconds ago   Up 2 seconds   80/tcp, 0.0.0.0:8009->8080/tcp                             ng
dba395715a34   34d6ab3660af   "/entrypoint.sh"         7 minutes ago   Up 7 minutes   9191/tcp, 0.0.0.0:8008->8001/tcp, 0.0.0.0:8006->8005/tcp   maas

  • 使用curl ip+port看是否可以訪問成功
shd:maas_qa_backend shenhaodong$  curl 127.0.0.1:8009
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title>Page not found at /</title>
  <meta name="robots" content="NONE,NOARCHIVE">
  <style type="text/css">
    html * { padding:0; margin:0; }
    body * { padding:10px 20px; }
    body * * { padding:0; }
    body { font:small sans-serif; background:#eee; color:#000; }
    body>div { border-bottom:1px solid #ddd; }
    h1 { font-weight:normal; margin-bottom:.4em; }
    h1 span { font-size:60%; color:#666; font-weight:normal; }
    table { border:none; border-collapse: collapse; width:100%; }
    td, th { vertical-align:top; padding:2px 3px; }
    th { width:12em; text-align:right; color:#666; padding-right:.5em; }
    #info { background:#f6f6f6; }
    #info ol { margin: 0.5em 4em; }
    #info ol li { font-family: monospace; }
    #summary { background: #ffc; }
    #explanation { background:#eee; border-bottom: 0px none; }
  </style>
</head>
<body>
  <div id="summary">
    <h1>Page not found <span>(404)</span></h1>
    <table class="meta">
      <tr>
        <th>Request Method:</th>
        <td>GET</td>
      </tr>
      <tr>
        <th>Request URL:</th>
        <td>http://127.0.0.1:8009/</td>
      </tr>
      
    </table>
  </div>
  <div id="info">
    
      <p>
      Using the URLconf defined in <code>maas_qa_backend.urls</code>,
      Django tried these URL patterns, in this order:
      </p>
      <ol>
        
          <li>
            
                admin/
                
            
          </li>
        
          <li>
            
                ^swagger(?P&lt;format&gt;\.json|\.yaml)$
                [name='schema-json']
            
          </li>
        
          <li>
            
                swagger/
                [name='schema-swagger-ui']
            
          </li>
        
          <li>
            
                redoc/
                [name='schema-redoc']
            
          </li>
        
          <li>
            
                api/common/select/detail
                
            
          </li>
        
          <li>
            
                api/users/
                
            
          </li>
        
          <li>
            
                api/productlines/
                
            
          </li>
        
          <li>
            
                api/project/
                
            
          </li>
        
          <li>
            
                api/projects/
                
            
          </li>
        
          <li>
            
                api/home/
                
            
          </li>
        
      </ol>
      <p>
        
        The empty path didn't match any of these.
      </p>
    
  </div>

  <div id="explanation">
    <p>
      You're seeing this error because you have <code>DEBUG = True</code> in
      your Django settings file. Change that to <code>False</code>, and Django
      will display a standard 404 page.
    </p>
  </div>
</body>
</html>


over

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市屑柔,隨后出現(xiàn)的幾起案子屡萤,更是在濱河造成了極大的恐慌,老刑警劉巖掸宛,帶你破解...
    沈念sama閱讀 216,470評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件死陆,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)措译,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評論 3 392
  • 文/潘曉璐 我一進(jìn)店門别凤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人领虹,你說我怎么就攤上這事规哪。” “怎么了塌衰?”我有些...
    開封第一講書人閱讀 162,577評論 0 353
  • 文/不壞的土叔 我叫張陵诉稍,是天一觀的道長。 經(jīng)常有香客問我最疆,道長杯巨,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,176評論 1 292
  • 正文 為了忘掉前任努酸,我火速辦了婚禮服爷,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘获诈。我一直安慰自己仍源,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,189評論 6 388
  • 文/花漫 我一把揭開白布烙荷。 她就那樣靜靜地躺著镜会,像睡著了一般。 火紅的嫁衣襯著肌膚如雪终抽。 梳的紋絲不亂的頭發(fā)上戳表,一...
    開封第一講書人閱讀 51,155評論 1 299
  • 那天,我揣著相機(jī)與錄音昼伴,去河邊找鬼匾旭。 笑死,一個胖子當(dāng)著我的面吹牛圃郊,可吹牛的內(nèi)容都是我干的价涝。 我是一名探鬼主播,決...
    沈念sama閱讀 40,041評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼持舆,長吁一口氣:“原來是場噩夢啊……” “哼色瘩!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起逸寓,我...
    開封第一講書人閱讀 38,903評論 0 274
  • 序言:老撾萬榮一對情侶失蹤居兆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后竹伸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體泥栖,經(jīng)...
    沈念sama閱讀 45,319評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,539評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了吧享。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片魏割。...
    茶點故事閱讀 39,703評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖钢颂,靈堂內(nèi)的尸體忽然破棺而出钞它,到底是詐尸還是另有隱情,我是刑警寧澤甸陌,帶...
    沈念sama閱讀 35,417評論 5 343
  • 正文 年R本政府宣布须揣,位于F島的核電站,受9級特大地震影響钱豁,放射性物質(zhì)發(fā)生泄漏耻卡。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,013評論 3 325
  • 文/蒙蒙 一牲尺、第九天 我趴在偏房一處隱蔽的房頂上張望卵酪。 院中可真熱鬧,春花似錦谤碳、人聲如沸溃卡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,664評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽瘸羡。三九已至,卻和暖如春搓茬,著一層夾襖步出監(jiān)牢的瞬間犹赖,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,818評論 1 269
  • 我被黑心中介騙來泰國打工卷仑, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留峻村,地道東北人。 一個月前我還...
    沈念sama閱讀 47,711評論 2 368
  • 正文 我出身青樓锡凝,卻偏偏與公主長得像粘昨,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子窜锯,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,601評論 2 353

推薦閱讀更多精彩內(nèi)容