五、使用Dockerfile创建镜像

编辑本文章

5.1、基本结构

  1. 基础镜像信息,FROM指定基础镜像
  2. 维护者信息,MAINTAINER 添加维护者信息
  3. 镜像操作指令,RUN指令将对镜像执行跟随命令,每运行一条RUN指令,镜像新添加一层并提交
  4. 容器启动时指令,CMD指令,来指定运行容器时的操作命令

5.2、指令

FROM

格式:FROM <image>或FROM <image>:<tag>
FROM scratch

scratch表示从空白镜像传家

MAINTAINER

格式:MAINTAINER <name>,指定维护者信息

RUN

格式:RUN <command>或RUN ["executable","param1","paraam2"]

command方式是在shell终端下运行,即/bin/sh -c

第二种使用exec方式执行,如:RUN ["/bin/bash","-c","echo hello"]

每运行一条RUN指令,将在当前镜像基础上执行指定命令,并提交新镜像。当命令较长时,可用"\"来换行

CMD

格式:

  CMD ["executable","param1","param2"],使用exec方式执行,推荐

  CMD command param1 param2在/bin/sh中执行,提供给需要交互的应用

  CMD ["param1","param2"]提供给ENTRYPOINT的默认参数

注:

  每个Dockerfile只能有一条cmd命令,指定了多行将只有最后一行被执行,若启动时用户指定了运行命令,将覆盖CMD命令

EXPOSE

格式:EXPOSE <PORT> [<PORT>...]

指定docker服务暴露的端口号,以供互联网访问,在启动容器时通过-P参数来自动分配一个端口转发到指定端口,用-p则具体指定那个本地端口与之映射

ENV

格式:ENV <key> <value>指定一个环境变量,会被后续RUN指令使用,并在容器运行时保持

ADD

格式:ADD <src> <dest>

复制指定<src>到容器中的<dest>。src可以时Dockerfile所在目录的一个相当路径(文件或目录),也可以是一个RUL,或一个tar文件(tar文件将自动解压为目录)

COPY

格式:COPY <src> <dest>

复制本地主机的<src>为容器中的<dest>。目标路径不存在将自动创建

源路径为本地目录时,推荐使用COPY

ENTRYPOINT

格式1:ENTRYPOINT ["executable","param1","param2"]

格式2(shell中执行):ENTRYPOINT command param1 param2

配置容器启动后执行的命令,该命令不会被docker run时提供的参数覆盖。一个Dockerfile只能有一个ENTRYPOINT,多个时最后一个生效

VOLUME

格式:VOLUME ["/data"]

创建一个可以从本地主机或其他容器挂载的挂载点,一般用来存放数据库或需要保持的数据等。

本地挂载到/var/lib/docker/volumes/ID/_data下

USER

格式:USER daemon

指定容器运行的用户名或UID,后续的RUN命令也会使用该用户运行。

当容器不需要管理员来运行时,可以指定该参数,且可以在之前创建所需用户,如:RUN groupadd -r postgres && useradd -r -g postgres postgres

需要临时管理员权限用gosu,不推荐sudo

WORKDIR

格式:WORKDIR /path/to/workdir

为后续RUN,CMD,ENTRYPOINT指定工作目录。可以有多个WORKDIR指令,当后续命令为相当路径时,则会基于之前的路径

ONBUILD

格式:ONBUILD [INSTRUCTION]

当所创建的镜像为其他新创建镜像的基础镜像时,使用该指令。

5.3、创建镜像

格式:docker build [选项] [Dockerfile所在路径]

dockerfile文件名必须为:Dockerfile

如:docker build -t build_repo:first_image /tmp/docker_builder/

该命令将读取指定路径下的dockerfile文件,并将该路径下所有内容发送给docker服务端,由服务端来创建镜像,所以放置Dockerfile的目录建议为空

也可以在路径下放置一个.dockerignore文件,来让Docker忽略指定目录和文件

可以用-t参数来指定镜像标签信息

 5.4、基于centos安装ssh服务示例Dockerfile文件

FROM centos
RUN yum install openssh-server -y
RUN /bin/echo "123.com" | passwd --stdin root

RUN ssh-keygen -q -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key -N ''\
ssh-keygen -q -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N ''\
ssh-keygen -t dsa -f /etc/ssh/ssh_host_ed25519_key -N ''
EXPOSE 22
CMD ["/usr/sbin/sshd","-D"]

修改版本:参考

FROM centos
RUN yum install openssh-server wget net-tools -y; \
wget -P /etc/yum.repos.d http://mirrors.163.com/.help/CentOS7-Base-163.repo; \
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup; \
mv /etc/yum.repos.d/CentOS7-Base-163.repo /etc/yum.repos.d/CentOS-Base.repo; \
yum clean all;

RUN /bin/echo "123.com" | passwd --stdin root;\
/bin/echo "#!/bin/bash" >> /run.sh;\
/bin/echo "/usr/sbin/init" >> /run.sh;\
/bin/echo "/usr/sbin/sshd -D" >> /run.sh;\
chmod +x /run.sh;


RUN ssh-keygen -q -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key -N '';\
ssh-keygen -q -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N '';\
ssh-keygen -t dsa -f /etc/ssh/ssh_host_ed25519_key -N '';



RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;

EXPOSE 22

VOLUME [ "/mnt" ]

CMD ["/run.sh"]
View Code

 

docker build -t centos7/centos_ssh:v1 ./build_centos7

[root@docker build_centos7]# docker build -t centos7/centos_ssh:v1 .
Sending build context to Docker daemon 2.048 kB
Step 1/6 : FROM centos
 ---> 1e1148e4cc2c
Step 2/6 : RUN yum install openssh-server -y
 ---> Running in d81bc11cb6ce

Loaded plugins: fastestmirror, ovl
Determining fastest mirrors
 * base: mirrors.cqu.edu.cn
 * extras: mirrors.cqu.edu.cn
 * updates: mirrors.njupt.edu.cn
http://mirrors.njupt.edu.cn/centos/7.6.1810/updates/x86_64/repodata/364a1a71327acdcb5de6f3bd5380598af7c9ecdf742dc768534e5170f27152e1-primary.sqlite.bz2: [Errno 12] Timeout on http://10.10.254.10/cache/5/02/mirrors.njupt.edu.cn/26c36252e7c97e4fb5b8f6abf23a4f23/364a1a71327acdcb5de6f3bd5380598af7c9ecdf742dc768534e5170f27152e1-primary.sqlite.bz2: (28, 'Connection timed out after 30970 milliseconds')
Trying other mirror.
Resolving Dependencies
--> Running transaction check
---> Package openssh-server.x86_64 0:7.4p1-16.el7 will be installed
--> Processing Dependency: openssh = 7.4p1-16.el7 for package: openssh-server-7.4p1-16.el7.x86_64
--> Processing Dependency: fipscheck-lib(x86-64) >= 1.3.0 for package: openssh-server-7.4p1-16.el7.x86_64
--> Processing Dependency: libwrap.so.0()(64bit) for package: openssh-server-7.4p1-16.el7.x86_64
--> Processing Dependency: libfipscheck.so.1()(64bit) for package: openssh-server-7.4p1-16.el7.x86_64
--> Running transaction check
---> Package fipscheck-lib.x86_64 0:1.4.1-6.el7 will be installed
--> Processing Dependency: /usr/bin/fipscheck for package: fipscheck-lib-1.4.1-6.el7.x86_64
---> Package openssh.x86_64 0:7.4p1-16.el7 will be installed
---> Package tcp_wrappers-libs.x86_64 0:7.6-77.el7 will be installed
--> Running transaction check
---> Package fipscheck.x86_64 0:1.4.1-6.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package                  Arch          Version               Repository   Size
================================================================================
Installing:
 openssh-server           x86_64        7.4p1-16.el7          base        458 k
Installing for dependencies:
 fipscheck                x86_64        1.4.1-6.el7           base         21 k
 fipscheck-lib            x86_64        1.4.1-6.el7           base         11 k
 openssh                  x86_64        7.4p1-16.el7          base        510 k
 tcp_wrappers-libs        x86_64        7.6-77.el7            base         66 k

Transaction Summary
================================================================================
Install  1 Package (+4 Dependent packages)

Total download size: 1.0 M
Installed size: 3.0 M
Downloading packages:
warning: /var/cache/yum/x86_64/7/base/packages/fipscheck-lib-1.4.1-6.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Public key for fipscheck-lib-1.4.1-6.el7.x86_64.rpm is not installed
--------------------------------------------------------------------------------
Total                                              211 kB/s | 1.0 MB  00:05     
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Importing GPG key 0xF4A80EB5:
 Userid     : "CentOS-7 Key (CentOS 7 Official Signing Key) <security@centos.org>"
 Fingerprint: 6341 ab27 53d7 8a78 a7c2 7bb1 24c6 a8a7 f4a8 0eb5
 Package    : centos-release-7-6.1810.2.el7.centos.x86_64 (@CentOS)
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : fipscheck-1.4.1-6.el7.x86_64                                 1/5 
  Installing : fipscheck-lib-1.4.1-6.el7.x86_64                             2/5 
  Installing : openssh-7.4p1-16.el7.x86_64                                  3/5 
  Installing : tcp_wrappers-libs-7.6-77.el7.x86_64                          4/5 
  Installing : openssh-server-7.4p1-16.el7.x86_64                           5/5 
  Verifying  : fipscheck-lib-1.4.1-6.el7.x86_64                             1/5 
  Verifying  : tcp_wrappers-libs-7.6-77.el7.x86_64                          2/5 
  Verifying  : fipscheck-1.4.1-6.el7.x86_64                                 3/5 
  Verifying  : openssh-7.4p1-16.el7.x86_64                                  4/5 
  Verifying  : openssh-server-7.4p1-16.el7.x86_64                           5/5 

Installed:
  openssh-server.x86_64 0:7.4p1-16.el7                                          

Dependency Installed:
  fipscheck.x86_64 0:1.4.1-6.el7      fipscheck-lib.x86_64 0:1.4.1-6.el7        
  openssh.x86_64 0:7.4p1-16.el7       tcp_wrappers-libs.x86_64 0:7.6-77.el7     

Complete!
 ---> 6d684fb0a9ac
Removing intermediate container d81bc11cb6ce
Step 3/6 : RUN /bin/echo "123.com" | passwd --stdin root
 ---> Running in 3af4d55f58c3

Changing password for user root.
passwd: all authentication tokens updated successfully.
 ---> 7f4b95ff818b
Removing intermediate container 3af4d55f58c3
Step 4/6 : RUN ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key     && ssh-keygen -t rsa -f /etc/ssh/ssh_host_ecdsa_key     && ssh-keygen -t rsa -f /etc/ssh/ssh_host_ed25519_key
 ---> Running in bd08aeeab115

Enter passphrase (empty for no passphrase): Enter same passphrase again: Generating public/private rsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_rsa_key.
Your public key has been saved in /etc/ssh/ssh_host_rsa_key.pub.
The key fingerprint is:
SHA256:rlMrIl6z+X/NtBNqlqh3qrOe42r4UWIjLqMOBD5HMMM root@d81bc11cb6ce
The key's randomart image is:
+---[RSA 2048]----+
|.+               |
| E+              |
|.  .             |
|o .              |
| +..+ . S        |
|..oo + ..   o    |
|+ ..+  ..o * o   |
|ooo.o==o+ B =    |
|oo.+=*X@o*   .   |
+----[SHA256]-----+
Enter passphrase (empty for no passphrase): Enter same passphrase again: Generating public/private rsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_ecdsa_key.
Your public key has been saved in /etc/ssh/ssh_host_ecdsa_key.pub.
The key fingerprint is:
SHA256:COQWXdq/KSXOPwzXL8Dafi4hur9s60PvlzeX6g6/640 root@d81bc11cb6ce
The key's randomart image is:
+---[RSA 2048]----+
|    o. ..        |
|   o ..o         |
|    + . .        |
|   . . . .       |
|      . S.o.     |
|       o+o=o.    |
|       o+Oo+ o  .|
|      ..+o* B *..|
|      .=**+*=E++ |
+----[SHA256]-----+
Enter passphrase (empty for no passphrase): Enter same passphrase again: Generating public/private rsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_ed25519_key.
Your public key has been saved in /etc/ssh/ssh_host_ed25519_key.pub.
The key fingerprint is:
SHA256:nvbQqpuF861eqqK7lSFR0NmhUkoDO3O20W/JGXICiYk root@d81bc11cb6ce
The key's randomart image is:
+---[RSA 2048]----+
|o+=+oo..         |
|Eo.Bo..          |
|+ B = o          |
| = = * +         |
|  o . * S        |
|   . + o o       |
|    o o * o      |
|   ..  * B       |
|  ++ .==*.o      |
+----[SHA256]-----+
 ---> 42573e81d3cf
Removing intermediate container bd08aeeab115
Step 5/6 : EXPOSE 22
 ---> Running in 2ea14e1bb964
 ---> 9da1eacc656d
Removing intermediate container 2ea14e1bb964
Step 6/6 : CMD /usr/sbin/sshd -D
 ---> Running in bab91df15d9e
 ---> 109d6739004c
Removing intermediate container bab91df15d9e
Successfully built 109d6739004c
[root@docker build_centos7]#
View Code

启动:docker run -it -d -p 222:22 --name ssh 109d6739004c    这里为嘛不能用centos7/centos_ssh,非要用IMAGE ID

用putty登陆,端口是上面映射的222

可正常登陆

Dockerfile创建nginx服务

命令:docker build -t centos7:nginx .

default.conf文件是nginx的配置文件

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
    location /static/ {
        root /var/www;
    }
    location / {
        include uwsgi_params;
        uwsgi_read_timeout 3600;
        uwsgi_pass 127.0.0.1:8080;
    }

    #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;
    #}
}
View Code

run.sh是容器启动时运行的程序

#!/bin/bash
/usr/sbin/sshd &
/usr/sbin/nginx &
/usr/bin/ping 127.0.0.1 > /dev/null
View Cod

dockerfile

FROM centos7:ssh

#修改时区
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

WORKDIR /var/tmp
COPY run.sh /run.sh

RUN yum install -y ntp wget openssl &&\
    wget http://nginx.org/packages/rhel/7/x86_64/RPMS/nginx-1.14.2-1.el7_4.ngx.x86_64.rpm &&\
    rpm -ivh nginx-1.14.2-1.el7_4.ngx.x86_64.rpm &&\
    rm -rf /etc/nginx/conf.d/* &&\
    chmod 755 /run.sh
    

COPY default.conf /etc/nginx/conf.d/

VOLUME ["/var/log/nginx","/var/www"]

CMD ["/run.sh"]

EXPOSE 80
EXPOSE 443
View Code

 查看创建好的镜像

 启动:docker run -d -p 222:22 -p 80:80 centos7:nginx

访问宿主机的80端口,可访问容器中的nginx服务

 

posted @ 2019-01-09 15:16  丫丫625202  阅读(486)  评论(0编辑  收藏  举报