docker實驗一:在docker執行nginx

docker實驗一:在docker執行nginx

教程參考http://www.runoob.com/docker/docker-install-nginx.html
由於菜鳥上的教程很多細節都沒寫出來,在這裡儘量把細節都記錄下來。

目標:通過docker執行nginx
前提:瞭解nginx的基本用法,瞭解docker基本指令


step1:宿主機準備

[email protected]:/opt/docker_nginx# docker pull nginx
...
[email protected]:/opt/docker_nginx# ls
conf  log  www

conf存放nginx的配置檔案,log存放nginx的日誌,www存放模板檔案,見下圖

[email protected]:/opt/docker_nginx# tree 
.
├── conf
│   └── nginx.conf
├── log
│   ├── access.log
│   └── error.log
└── www
└── index.html

以下是nginx.conf內容

user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# SSL Settings
##
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
##
# Logging Settings
##
access_log /opt/nginx/log/access.log;
error_log /opt/nginx/log/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
##
# Virtual Host Configs
##
server {
listen 80 default_server;
listen [::]:80 default_server;
root /opt/nginx/www;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
}
}

以上這個配置從nginx的預設配置檔案複製出來的,改動log、root相關內容,即:

...
access_log /opt/nginx/log/access.log;
error_log /opt/nginx/log/error.log;
...
root /opt/nginx/www;
...

index.html

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
</head>
<body>
<h2>Hello docker nginx</h1>
</body>
</html>

step2:

啟動容器

[email protected]:/opt/docker_nginx# docker run -p 8093:80 --name mynginx  -v $PWD/conf/nginx.conf:/etc/nginx/nginx.conf -v $PWD/www:/opt/nginx/www -v $PWD/log:/opt/nginx/log  -d nginx
026f7dc3dfa4362210a5273775e01222c6b622a9298ec20e9d53f46d9bc72f20

命令說明:

  -p 8093:80:將容器的80埠對映到主機的8093埠
-name mynginx:將容器命名為mynginx
-v $PWD/conf/nginx.conf:/etc/nginx/nginx.conf:將主機中當前目錄下的nginx.conf掛載到容器的/etc/nginx/nginx.conf
-v $PWD/www:/opt/nginx/www:將主機中當前目錄下的www掛載到容器的/opt/nginx/www,參考nginx.conf的root配置
-v $PWD/log:/opt/nginx/log:將主機中當前目錄下的log掛載到容器的/opt/nginx/log,參考nginx.conf的log配置

step3:測試是否正常

在主機瀏覽器開啟
這裡寫圖片描述