# 安裝Nginx on Docker

## 取得映像檔

輸入`docker images`查詢目前擁有的映像檔

```
root@vm:/home/jennifer# docker images
REPOSITORY                                    TAG                 IMAGE ID            CREATED             SIZE
python                                        3.5-alpine          d15e7a9f900e        3 weeks ago         68.1MB
cassandra                                     latest              604151722441        2 months ago        379MB
alpine                                        3.11                f70734b6a266        2 months ago        5.61MB
nginx                                         1.13.3-alpine       ba60b24dbad5        2 years ago         15.5MB
```

若沒有nginx映像檔，可上[DockerHub](https://hub.docker.com/_/nginx)查詢，選擇版本並`docker pull nginx:[tag]`拉映像檔到自己的機器上，Docker Hub上也會有使用範例

```
root@vm:/home/jennifer# docker pull nginx:1.18
1.18: Pulling from library/nginx
8559a31e96f4: Pull complete
9a38be3aab21: Pull complete
522e5edd83fa: Pull complete
2ccf5a90baa6: Pull complete
Digest: sha256:159aedcc6acb8147c524ec2d11f02112bc21f9e8eb33e328fb7c04b05fc44e1c
Status: Downloaded newer image for nginx:1.18
```

## 啟動容器

#### 情境一：使用Docker Bridge Network，並設定port mapping (host 8880 port <-> 容器 80port)

```
root@vm:/home/jennifer# docker run --name some-nginx -d -p 8880:80 nginx:1.18
```

輸入`http://host-ip:8880`，若有出現nginx畫面代表成功

![](https://1309293527-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lt87Z2Vgpk1kICGRgqP%2F-MB34WlRXXmxTY4nYTCD%2F-MB35AsfSpuSx2Pck9mF%2Fnginx.png?alt=media\&token=c774079a-a7fc-40d9-ab34-cc9bcd3b275e)

####

#### 情境二：使用Docker Bridge Network，並設定port mapping，`-P`表示主機的port不指定，由電腦隨機取得

```
root@vm:/home/jennifer# docker run --name test-nginx -d -P nginx:1.18
87b059c8b554bd69796ff509a790b5f0684cf88a0ea2e22eb4ec767413fffacf

root@vm:/home/jennifer# docker ps
CONTAINER ID        IMAGE                            COMMAND                  CREATED             STATUS              PORTS                                                                                        NAMES
87b059c8b554        nginx:1.18                       "nginx -g 'daemon of…"   3 seconds ago       Up 2 seconds        0.0.0.0:32768->80/tcp                                                                        test-nginx

```

經`docker ps`查詢容器對應的主機port為32768輸入`http://host-ip:32768`，若有出現nginx畫面代表成功

![](https://1309293527-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lt87Z2Vgpk1kICGRgqP%2F-MB74BobSJPdt4S5mWgb%2F-MB74jRHR_1g5Ye0Ez2k%2Fnginx2.png?alt=media\&token=fdfaf082-eb7b-4a8e-9efb-a0422d88480b)

#### 情境三：使用host網路，並volume設定檔及NFS資料夾

```
root@vm:/home/jennifer# docker volume create --driver local \
--opt type=nfs \
--opt o=nfsvers=3,addr=192.168.0.0,rw \
--opt device=:/nfstemp \
volume_nfs    #這個指令是用來建立docker data volume

root@vm:/home/jennifer# docker run -d --net=host --restart=always \
-v /var/docker_volume/nginx/default.conf:/etc/nginx/conf.d/default.conf \
-v volume_nfs:/tmp:ro nginx:1.18  #這個指令是用來建立nginx容器
```

## 調整nginx設定檔

我們用`docker exec -it b5e1 bash`進到nginx的容器來看看設定檔（b5e1是某個nginx容器的ID，完整的ID是b5e16239b697，可只輸入前幾碼），再查詢、顯示設定檔的內容

```
root@vm:/home/jennifer# docker exec -it b5e1 bash   # 進入容器並執行BASH


root@b5e16239b697:/etc/nginx# nginx -t   # 查詢nginx設定檔的位置
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

root@b5e16239b697:/etc/nginx# cat /etc/nginx/nginx.conf  # 顯示設定檔內容

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}
```

主機的配置則是default.conf，在容器內執行`cat /etc/nginx/conf.d/default.conf`查看內容

```
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #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   /usr/share/nginx/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;
    #}
}
```

以下是一個完整的default.conf，描述nginx如何處理request

```
server {
    listen       80;
    server_name  192.168.0.100;

    location ~* ^/book_api/(.*)$ {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://192.168.0.100:8801/$1$is_args$args;
        client_max_body_size 5M;
        rewrite "^/book_api/(.*)" /$1 break;
    }    

    location /fs/ {
        alias   /tmp/my_fs/;
        try_files $uri default.jpg =404;
    }
    
}
```

下面這段內容表示，當request的子目錄是book\_api的時候，例如 `http://host-ip/book_api/` 或 `http://host-ip/book_api/query?id=3` ，都將內容再導向至`http://192.168.0.100:8801`

另外`client_max_body_size 5M`表示允許上傳的檔案大小為5M

```
    location ~* ^/book_api/(.*)$ {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://192.168.0.100:8801/$1$is_args$args;
        client_max_body_size 5M;
        rewrite "^/book_api/(.*)" /$1 break;
    }  
```

下面這段內容，表示當request的子目錄是fs的時候，例如 `http://localhost-ip/fs/a.png`，事實上是返回 `/tmp/my_fs/a.png` 給前端

```
    location /fs/ {
        alias   /tmp/my_fs/;
        try_files $uri default.jpg =404;
    }
```
