基本结构

Dockerfile 由一行行命令语句组成,并且支持以 # 开头的注释行。

一般的,Dockerfile 分为四部分:基础镜像信息、维护者信息、镜像操作指令和容器启动时执行指令。

例如

  1. # This dockerfile uses the ubuntu image
  2. # VERSION 2 - EDITION 1
  3. # Author: docker_user
  4. # Command format: Instruction [arguments / command] ..
  5. # Base image to use, this must be set as the first line
  6. FROM ubuntu
  7. # Maintainer: docker_user <docker_user at email.com> (@docker_user)
  8. MAINTAINER docker_user docker_user@email.com
  9. # Commands to update the image
  10. RUN echo "deb http://archive.ubuntu.com/ubuntu/ raring main universe" >> /etc/apt/sources.list
  11. RUN apt-get update && apt-get install -y nginx
  12. RUN echo "\ndaemon off;" >> /etc/nginx/nginx.conf
  13. # Commands when creating a new container
  14. CMD /usr/sbin/nginx

其中,一开始必须指明所基于的镜像名称,接下来推荐说明维护者信息。

后面则是镜像操作指令,例如 RUN 指令,RUN 指令将对镜像执行跟随的命令。每运行一条 RUN 指令,镜像添加新的一层,并提交。

最后是 CMD 指令,来指定运行容器时的操作命令。

下面是一个更复杂的例子

  1. # Nginx
  2. #
  3. # VERSION 0.0.1
  4. FROM ubuntu
  5. MAINTAINER Victor Vieux <victor@docker.com>
  6. RUN apt-get update && apt-get install -y inotify-tools nginx apache2 openssh-server
  7. # Firefox over VNC
  8. #
  9. # VERSION 0.3
  10. FROM ubuntu
  11. # Install vnc, xvfb in order to create a 'fake' display and firefox
  12. RUN apt-get update && apt-get install -y x11vnc xvfb firefox
  13. RUN mkdir /.vnc
  14. # Setup a password
  15. RUN x11vnc -storepasswd 1234 ~/.vnc/passwd
  16. # Autostart firefox (might not be the best way, but it does the trick)
  17. RUN bash -c 'echo "firefox" >> /.bashrc'
  18. EXPOSE 5900
  19. CMD ["x11vnc", "-forever", "-usepw", "-create"]
  20. # Multiple images example
  21. #
  22. # VERSION 0.1
  23. FROM ubuntu
  24. RUN echo foo > bar
  25. # Will output something like ===> 907ad6c2736f
  26. FROM ubuntu
  27. RUN echo moo > oink
  28. # Will output something like ===> 695d7793cbe4
  29. # You᾿ll now have two images, 907ad6c2736f with /bar, and 695d7793cbe4 with
  30. # /oink.