以运行 busybox容器为线索,跟踪docekr启动容器的过程,
vito@caas:~$ docker run -it busybox /bin/sh
1、docker 客户端解析
Docker client主要的工作是通过解析用户所提供的一系列参数后,docker的入口函数main,在入口函数中处理传入的参数,并把参数转化为cobra的command类型,最后通过cobra调用相应的方法。
/docker/api/client/container/run.go
// NewRunCommand create a new `docker run` command
func NewRunCommand(dockerCli *client.DockerCli) *cobra.Command {
var opts runOptions
var copts *runconfigopts.ContainerOptions
cmd := &cobra.Command{
Use: "run [OPTIONS] IMAGE [COMMAND] [ARG...]",
Short: "Run a command in a new container",
Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
copts.Image = args[0]
if len(args) > 1 {
copts.Args = args[1:]
}
//run 命令对应的客户端方法
return runRun(dockerCli, cmd.Flags(), &opts, copts)
},
}
客户端中预准备的步骤:
func runRun(dockerCli *client.DockerCli, flags *pflag.FlagSet, opts *runOptions, copts *runconfigopts.ContainerOptions) error {
stdout, stderr, stdin := dockerCli.Out(), dockerCli.Err(), dockerCli.In()
//实例化一个客户端,用于发送run命令请求
client := dockerCli.Client()
// TODO: pass this as an argument
cmdPath := "run"
//定义错误信息
var (
flAttach *opttypes.ListOpts
ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d")
ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm")
ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d")
)
//解析命令和参数
//config :主要是与主机无关的配置数据,比如hostname,user;默认omitempty设置,如果为空置则忽略字段。
//hostConfig : 与主机相关的配置。
//networkingConfig :网络相关的配置。
config, hostConfig, networkingConfig, err := runconfigopts.Parse(flags, copts)
fmt.Println('-----------print config:/n',config, hostConfig, networkingConfig)
分析:
config文件的结构定义在container包中,具体路径如下:
docker/vendor/github.com/docker/engine-api/types/container/config.go
docker/vendor/github.com/docker/engine-api/types/container/host_config.go
- container.Config :包含着容器的配置数据,主要是与主机无关的配置数据,比如hostname,user;默认omitempty设置,如果为空置则忽略字段。
type Config struct {
Hostname string // Hostname 容器内的主机名
Domainname string // Domainname 域名服务器名称
//容器内用户名,用于运行CMD命令
User string // User that will run the command(s) inside the container
AttachStdin bool // Attach the standard input, makes possible user interaction
AttachStdout bool // Attach the standard output 是否附加标准输出
AttachStderr bool // Attach the standard error
ExposedPorts map[nat.Port]struct{} `json:",omitempty"` // List of exposed ports 容器内暴露的端口号
Tty bool // Attach standard streams to a tty, including stdin if it is not closed.是否分配一个伪终端
OpenStdin bool // Open stdin 在没有附加标准输入是,是否依然打开标准输入
//如该为真,用户关闭标准输入,容器的标准输入关闭
StdinOnce bool // If true, close stdin after the 1 attached client disconnects.
Env []string // List of environment variable to set in the container 环境变量
Cmd strslice.StrSlice // Command to run when starting the container 容器内运行的指令
Healthcheck *HealthConfig `json:",omitempty"` // Healthcheck describes how to check the container is healthy
ArgsEscaped bool `json:",omitempty"` // True if command is already escaped (Windows specific)
Image string // Name of the image as it was passed by the operator (eg. could be symbolic) 镜像名称
Volumes map[string]struct{} // List of volumes (mounts) used for the container 挂载目录
WorkingDir string // Current directory (PWD) in the command will be launched 容器内,进程指定的工作目录
Entrypoint strslice.StrSlice // Entrypoint to run when starting the container 覆盖镜像中默认的entrypoint
NetworkDisabled bool `json:",omitempty"` // Is network disabled 是否关闭容器网络功能
MacAddress string `json:",omitempty"` // Mac Address of the container MAC地址
//在dockerfile中定义的,指定的命令在容器构建时不执行,而是在镜像构建完成之后被出发执行
OnBuild []string // ONBUILD metadata that were defined on the image Dockerfile
Labels map[string]string // List of labels set to this container 容器中的labels
StopSignal string `json:",omitempty"` // Signal to stop a container
StopTimeout *int `json:",omitempty"` // Timeout (in seconds) to stop a container
Shell strslice.StrSlice `json:",omitempty"` // Shell for shell-form of RUN, CMD, ENTRYPOINT
}
- container.HostConfig: 与主机相关的配置信息。
type HostConfig struct {
// Applicable to all platforms
//从宿主机上绑定到容器的volume
Binds []string // List of volume bindings for this container
//用于写入容器ID的文件名
ContainerIDFile string // File (path) where the containerId is written
//配置容器的日志
LogConfig LogConfig // Configuration of the logs for this container
//容器的网络模式
NetworkMode NetworkMode // Network mode to use for the container
//容器绑定到宿主及的端口
PortBindings nat.PortMap // Port mapping between the exposed port (container) and the