Nginx的Docker镜像制作详解

一、环境描述

1. 宿主机

  • CPU:双核
  • 内存:4 GB
  • 硬盘:120 GB
  • IP地址:192.168.190.128
  • 操作系统:CentOS 7.4 x86_64 Minimal

2. Docker

3. 基础镜像

4. Nginx

  • 版本:1.12.2
  • 安装方式:YUM Repo

二、创建必要的文件

1. 创建服务启动脚本

当Nginx容器启动时,便会运行该脚本,启动Nginx服务。在shell中运行以下命令,创建start.sh脚本:

cat > /root/Downloads/start.sh << "EOF"
#! /bin/bash

# Source function library.
. /etc/rc.d/init.d/functions

if [ -L $0 ]; then
    initscript=`/bin/readlink -f $0`
else
    initscript=$0
fi

sysconfig=`/bin/basename $initscript`

if [ -f /etc/sysconfig/$sysconfig ]; then
    . /etc/sysconfig/$sysconfig
fi

nginx=${NGINX:-/usr/sbin/nginx}
prog=`/bin/basename $nginx`
conffile=${CONFFILE:-/etc/nginx/nginx.conf}
lockfile=${LOCKFILE:-/var/lock/subsys/nginx}
pidfile=${PIDFILE:-/var/run/nginx.pid}
SLEEPSEC=${SLEEPSEC:-1}
UPGRADEWAITLOOPS=${UPGRADEWAITLOOPS:-5}
CHECKSLEEP=${CHECKSLEEP:-3}
RETVAL=0

start() {
    echo -n $"Starting $prog: "

    daemon --pidfile=${pidfile} ${nginx} -c ${conffile}
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && touch ${lockfile}
    return $RETVAL
}

start

exit $RETVAL
EOF

2. 创建镜像源配置文件

Nginx有自己的官方镜像源,其中包含最新稳定版本的Nginx安装包。在shell中运行以下命令,添加Nginx官方镜像源:

cat > /root/Downloads/nginx.repo << "EOF"
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/6/$basearch/
gpgcheck=0
enabled=1
EOF

3. 创建MIME类型文件

mime.types文件能够定义Nginx能够处理的媒体文件类型。在shell中运行以下命令,创建mime.types文件:

cat > /root/Downloads/mime.types << "EOF"
types {
    text/html                             html htm shtml;
    text/css                              css;
    text/xml                              xml;
    image/gif                             gif;
    image/jpeg                            jpeg jpg;
    application/javascript                js;
    application/atom+xml                  atom;
    application/rss+xml                   rss;

    text/mathml                           mml;
    text/plain                            txt;
    text/vnd.sun.j2me.app-descriptor      jad;
    text/vnd.wap.wml                      wml;
    text/x-component                      htc;

    image/png                             png;
    image/tiff                            tif tiff;
    image/vnd.wap.wbmp                    wbmp;
    image/x-icon                          ico;
    image/x-jng                           jng;
    image/x-ms-bmp                        bmp;
    image/svg+xml                         svg svgz;
    image/webp                            webp;

    application/font-woff                 woff;
    application/java-archive              jar war ear;
    application/json                      json;
    application/mac-binhex40              hqx;
    application/msword                    doc;
    application/pdf                       pdf;
    application/postscript                ps eps ai;
    application/rtf                       rtf;
    application/vnd.apple.mpegurl         m3u8;
    application/vnd.ms-excel              xls;
    application/vnd.ms-fontobject         eot;
    application/vnd.ms-powerpoint         ppt;
    application/vnd.wap.wmlc              wmlc;
    application/vnd.google-earth.kml+xml  kml;
    application/vnd.google-earth.kmz      kmz;
    application/x-7z-compressed           7z;
    application/x-cocoa                   cco;
    application/x-java-archive-diff       jardiff;
    application/x-java-jnlp-file          jnlp;
    application/x-makeself                run;
    application/x-perl                    pl pm;
    application/x-pilot                   prc pdb;
    application/x-rar-compressed          rar;
    application/x-redhat-package-manager  rpm;
    application/x-sea                     sea;
    application/x-shockwave-flash         swf;
    application/x-stuffit                 sit;
    application/x-tcl                     tcl tk;
    application/x-x509-ca-cert            der pem crt;
    application/x-xpinstall               xpi;
    application/xhtml+xml                 xhtml;
    application/xspf+xml                  xspf;
    application/zip                       zip;

    application/octet-stream              bin exe dll;
    application/octet-stream              deb;
    application/octet-stream              dmg;
    application/octet-stream              iso img;
    application/octet-stream              msi msp msm;

    application/vnd.openxmlformats-officedocument.wordprocessingml.document    docx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet          xlsx;
    application/vnd.openxmlformats-officedocument.presentationml.presentation  pptx;

    audio/midi                            mid midi kar;
    audio/mpeg                            mp3;
    audio/ogg                             ogg;
    audio/x-m4a                           m4a;
    audio/x-realaudio                     ra;

    video/3gpp                            3gpp 3gp;
    video/mp2t                            ts;
    video/mp4                             mp4;
    video/mpeg                            mpeg mpg;
    video/quicktime                       mov;
    video/webm                            webm;
    video/x-flv                           flv;
    video/x-m4v                           m4v;
    video/x-mng                           mng;
    video/x-ms-asf                        asx asf;
    video/x-ms-wmv                        wmv;
    video/x-msvideo                       avi;
}
EOF

4. 创建Nginx配置文件

Nginx容器的配置文件存放在宿主机中,便于调整Nginx服务的配置项。在shell中运行以下命令,创建nginx.conf文件:

cat > /root/Downloads/nginx.conf << "EOF"
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;
}
EOF

5. 创建supervisor配置文件

supervisor是一种Linux的进程管理工具,Nginx容器会用其管理自身的后台服务。在shell中运行以下命令,创建supervisord.conf文件:

cat > /root/Downloads/supervisord.conf << "EOF"
[supervisord]
nodaemon=true

[program:nginx]
command=/bin/bash start.sh
EOF

三、制作Nginx镜像

1. 创建Dockerfile文件

在shell中运行以下命令,创建Dockerfile文件:

cat > /root/Downloads/Dockerfile << "EOF"
# 使用自建的CentOS 6.9基础镜像
FROM registry.cn-hangzhou.aliyuncs.com/ghoulich-centos/centos:6.9

# 镜像维护者
MAINTAINER ghoulich@aliyun.com

# 添加Nginx镜像源
COPY nginx.repo /etc/yum.repos.d/
RUN rpm --import http://nginx.org/keys/nginx_signing.key

# 安装Nginx
RUN yum install -y epel-release
RUN rpm --rebuilddb && yum install -y nginx supervisor
RUN mkdir -p /var/lib/nginx
COPY start.sh /
COPY supervisord.conf /etc/supervisord.conf

# 清理系统
RUN yum clean all

# 开放端口
EXPOSE 80

# 挂载数据、配置和日志目录
VOLUME ["/var/lib/nginx", "/etc/nginx", "/var/log/nginx"]

# 自动启动Nginx
CMD ["/usr/bin/supervisord"]
EOF

上述文件有两点需要注意:

  • 公开80端口,这是Nginx的默认服务端口。
  • 创建数据、配置和日志目录的挂载点,这样便可以通过宿主机直接编辑和查看Nginx容器的数据、配置和日志,即使删除容器,这些数据也不会丢失。

2. 创建Nginx镜像

在shell中执行以下命令,创建镜像(耗时较长):

cd /root/Downloads
docker build -t nginx:latest .

3. 查看镜像

在shell中查看镜像信息,若如下图所示,则表示镜像创建成功:

查看Nginx镜像的状态

四、上传镜像

1. 登录阿里云镜像库

在shell中运行以下命令:

docker login --username=ghoulich@aliyun.com registry.cn-hangzhou.aliyuncs.com

请根据实际情况,使用真实的用户名和密码。

2. 创建镜像标签

在shell中运行以下命令:

docker tag nginx:latest registry.cn-hangzhou.aliyuncs.com/ghoulich-centos/centos-6.9-nginx:1.12.2

3. 推送镜像

在shell中运行以下命令:

docker push registry.cn-hangzhou.aliyuncs.com/ghoulich-centos/centos-6.9-nginx:1.12.2

五、使用方法

1. 创建目录和文件

在宿主机中创建Nginx的数据、配置和日志目录,然后修改访问权限,最后拷贝配置文件:

mkdir -p /usr/local/nginx/{html,conf,logs}
mkdir -p /usr/local/nginx/conf/conf.d
chown -R 499:499 /usr/local/nginx/logs
cp /root/Downloads/{nginx.conf,mime.types} /usr/local/nginx/conf/

注意,499:499是Nginx容器中nginx用户的UID和GID,宿主机中没有这个用户。

2. 启动容器

在shell中运行以下命令,启动Nginx容器:

docker run --detach \
    --name nginx \
    --hostname nginx \
    --volume /usr/local/nginx/html:/var/lib/nginx \
    --volume /usr/local/nginx/conf:/etc/nginx \
    --volume /usr/local/nginx/logs:/var/log/nginx \
    --publish 80:80 \
    registry.cn-hangzhou.aliyuncs.com/ghoulich-centos/centos-6.9-nginx:1.12.2

有几个选项需要说明:

  • --volume:将Nginx容器的数据、配置和日志目录映射至宿主机的相应目录;
  • --publish:将Nginx容器的80端口映射至宿主机的80端口。

3. 验证测试

通过宿主机查看容器中运行的进程,若结果如下图所示,则表示Nginx容器启动成功:

查看Nginx容器的运行状态

4. 常用命令

在修改配置文件之后,需要重启Nginx服务才能生效,可以通过以下命令启动、停止和重启容器,也能达到同样的效果:

# 启动容器
docker start nginx
# 停止容器
docker stop nginx
# 重启容器
docker restart nginx