salt.modules.dockerng

Management of Docker Containers

2015.8.0 新版功能.

Why Make a Second Docker Execution Module?

We have received a lot of feedback on our Docker support. In the process of implementing recommended improvements, it became obvious that major changes needed to be made to the functions and return data. In the end, a complete rewrite was done.

The changes being too significant, it was decided that making a separate execution module and state module (called dockerng) would be the best option. This will give users a couple release cycles to modify their scripts, SLS files, etc. to use the new functionality, rather than forcing users to change everything immediately.

In the Carbon release of Salt (due in 2016), this execution module will take the place of the default Docker execution module, and backwards-compatible naming will be maintained for a couple releases after that to allow users time to replace references to dockerng with docker.

Installation Prerequisites

This execution module requires at least version 1.4.0 of both docker-py and Docker. docker-py can easily be installed using pip.install:

salt myminion pip.install docker-py>=1.4.0

Authentication

To push or pull images, credentials must be configured. Because a password must be used, it is recommended to place this configuration in Pillar data. The configuration schema is as follows:

docker-registries:
  <registry_url>:
    email: <email_address>
    password: <password>
    username: <username>

For example:

docker-registries:
  https://index.docker.io/v1/:
    email: foo@foo.com
    password: s3cr3t
    username: foo

Mulitiple registries can be configured. This can be done in one of two ways. The first way is to configure each registry under the docker-registries pillar key.

docker-registries:
  https://index.foo.io/v1/:
    email: foo@foo.com
    password: s3cr3t
    username: foo
  https://index.bar.io/v1/:
    email: foo@foo.com
    password: s3cr3t
    username: foo

The second way is to use separate pillar variables ending in -docker-registries:

foo-docker-registries:
  https://index.foo.io/v1/:
    email: foo@foo.com
    password: s3cr3t
    username: foo

bar-docker-registries:
  https://index.bar.io/v1/:
    email: foo@foo.com
    password: s3cr3t
    username: foo

Both methods can be combined; any registry configured under docker-registries or *-docker-registries will be detected.

Configuration Options

The following options can be set in the minion config:

  • docker.url: URL to the docker service (default: local socket).

  • docker.version: API version to use (default: currently 1.4 API).

  • docker.exec_driver: Execution driver to use, one of the following:
    • nsenter
    • lxc-attach
    • docker-exec

    See Executing Commands Within a Running Container.

Executing Commands Within a Running Container

Multiple methods exist for executing commands within Docker containers:

  • lxc-attach: Default for older versions of docker
  • nsenter: Enters container namespace to run command
  • docker-exec: Native support for executing commands in Docker containers (added in Docker 1.3)

Adding a configuration option (see config.get) called docker.exec_driver will tell Salt which execution driver to use:

docker.exec_driver: docker-exec

If this configuration option is not found, Salt will use the appropriate interface (either nsenter or lxc-attach) based on the Execution Driver value returned from docker info. docker-exec will not be used by default, as it is presently (as of version 1.6.2) only able to execute commands as the effective user of the container. Thus, if a USER directive was used to run as a non-privileged user, docker-exec would be unable to perform the action as root. Salt can still use docker-exec as an execution driver, but must be explicitly configured (as in the example above) to do so at this time.

If possible, try to manually specify the execution driver, as it will save Salt a little work.

This execution module provides functions that shadow those from the cmd module. They are as follows:

Detailed Function Documentation

salt.modules.dockerng.build(path=None, image=None, cache=True, rm=True, api_response=False, fileobj=None)

Builds a docker image from a Dockerfile or a URL

path
Path to directory on the Minion containing a Dockerfile
image
Image to be built, in repo:tag notation. If just the repository name is passed, a tag name of latest will be assumed. If building from a URL, this parameted can be omitted.
cache : True
Set to False to force the build process not to use the Docker image cache, and pull all required intermediate image layers
rm : True
Remove intermediate containers created during build
api_response : False
If True: an API_Response key will be present in the return data, containing the raw output from the Docker API.
fileobj
Allows for a file-like object containing the contents of the Dockerfile to be passed in place of a file path argument. This argument should not be used from the CLI, only from other Salt code.

RETURN DATA

A dictionary containing one or more of the following keys:

  • Id - ID of the newly-built image

  • Time_Elapsed - Time in seconds taken to perform the build

  • Intermediate_Containers - IDs of containers created during the course of the build process

    (Only present if rm=False)

  • Images - A dictionary containing one or more of the following keys:
    • Already_Pulled - Layers that that were already present on the Minion
    • Pulled - Layers that that were pulled

    (Only present if the image specified by the "image" argument was not present on the Minion, or if cache=False)

  • Status - A string containing a summary of the pull action (usually a message saying that an image was downloaded, or that it was up to date).

    (Only present if the image specified by the "image" argument was not present on the Minion, or if cache=False)

CLI Example:

salt myminion dockerng.build /path/to/docker/build/dir image=myimage:dev
salt myminion dockerng.build https://github.com/myuser/myrepo.git image=myimage:latest
salt.modules.dockerng.commit(name, image, message=None, author=None)

Commits a container, thereby promoting it to an image. Equivalent to running the docker commit Docker CLI command.

name
Container name or ID to commit
image
Image to be committed, in repo:tag notation. If just the repository name is passed, a tag name of latest will be assumed.
message
Commit message (Optional)
author
Author name (Optional)

RETURN DATA

A dictionary containing the following keys:

  • Id - ID of the newly-created image
  • Image - Name of the newly-created image
  • Time_Elapsed - Time in seconds taken to perform the commit

CLI Example:

salt myminion dockerng.commit mycontainer myuser/myimage
salt myminion dockerng.commit mycontainer myuser/myimage:mytag
salt.modules.dockerng.connect_container_to_network(container, network_id)

Connect container to network.

container
Container name or ID
network_id
ID of network

CLI Example:

salt myminion dockerng.connect_container_from_network web-1 1f9d2454d0872b68dd9e8744c6e7a4c66b86f10abaccc21e14f7f014f729b2bc
salt.modules.dockerng.copy_from(name, *args, **kwargs)

Copy a file from inside a container to the Minion

name
Container name
source
Path of the file on the container's filesystem
dest
Destination on the Minion. Must be an absolute path. If the destination is a directory, the file will be copied into that directory.
overwrite : False
Unless this option is set to True, then if a file exists at the location specified by the dest argument, an error will be raised.
makedirs : False
Create the parent directory on the container if it does not already exist.

RETURN DATA

A boolean (True if successful, otherwise False)

CLI Example:

salt myminion dockerng.copy_from mycontainer /var/log/nginx/access.log /home/myuser
salt.modules.dockerng.copy_to(name, *args, **kwargs)

Copy a file from the host into a container

name
Container name
source
File to be copied to the container. Can be a local path on the Minion or a remote file from the Salt fileserver.
dest
Destination on the container. Must be an absolute path. If the destination is a directory, the file will be copied into that directory.
exec_driver : None
If not passed, the execution driver will be detected as described above.
overwrite : False
Unless this option is set to True, then if a file exists at the location specified by the dest argument, an error will be raised.
makedirs : False
Create the parent directory on the container if it does not already exist.

RETURN DATA

A boolean (True if successful, otherwise False)

CLI Example:

salt myminion dockerng.copy_to mycontainer /tmp/foo /root/foo
salt.modules.dockerng.create(*args, **kwargs)

Create a new container

name
Name for the new container. If not provided, Docker will randomly generate one for you.
image
Image from which to create the container
command or cmd

Command to run in the container

Example: command=bash or cmd=bash

在 2015.8.1 版更改: cmd is now also accepted

hostname

Hostname of the container. If not provided, and if a name has been provided, the hostname will default to the name that was passed.

Example: hostname=web1

警告

If the container is started with network_mode=host, the hostname will be overridden by the hostname of the Minion.

domainname

Domain name of the container

Example: domainname=domain.tld

interactive : False

Leave stdin open

Example: interactive=True

tty : False

Attach TTYs

Example: tty=True

detach : True

If True, run command in the background (daemon mode)

Example: detach=False

user

User under which to run docker

Example: user=foo

memory : 0

Memory limit. Can be specified in bytes or using single-letter units (i.e. 512M, 2G, etc.). A value of 0 (the default) means no memory limit.

Example: memory=512M, memory=1073741824

memory_swap : -1

Total memory limit (memory plus swap). Set to -1 to disable swap. A value of 0 means no swap limit.

Example: memory_swap=1G, memory_swap=2147483648

mac_address

MAC address to use for the container. If not specified, a random MAC address will be used.

Example: mac_address=01:23:45:67:89:0a

network_disabled : False

If True, networking will be disabled within the container

Example: network_disabled=True

working_dir

Working directory inside the container

Example: working_dir=/var/log/nginx

entrypoint

Entrypoint for the container. Either a string (e.g. "mycmd --arg1 --arg2") or a Python list (e.g. "['mycmd', '--arg1', '--arg2']")

Example: entrypoint="cat access.log"

environment

Either a dictionary of environment variable names and their values, or a Python list of strings in the format VARNAME=value.

Example: "{'VAR1': 'value', 'VAR2': 'value'}", "['VAR1=value', 'VAR2=value']"

ports

A list of ports to expose on the container. Can be passed as comma-separated list or a Python list. If the protocol is omitted, the port will be assumed to be a TCP port.

Example: 1111,2222/udp, "['1111/tcp', '2222/udp']"

volumes : None

List of directories to expose as volumes. Can be passed as a comma-separated list or a Python list.

Example: volumes=/mnt/vol1,/mnt/vol2, volumes="[/mnt/vol1, /mnt/vol2]"

cpu_shares

CPU shares (relative weight)

Example: cpu_shares=0.5, cpu_shares=1

cpuset

CPUs on which which to allow execution, specified as a string containing a range (e.g. 0-3) or a comma-separated list of CPUs (e.g. 0,1).

Example: cpuset="0-3", cpuset="0,1"

client_timeout

Timeout in seconds for the Docker client. This is not a timeout for this function, but for receiving a response from the API.

注解

This is only used if Salt needs to pull the requested image.

labels

Add Metadata to the container. Can be a list of strings/dictionaries or a dictionary of strings (keys and values).

Example: labels=LABEL1,LABEL2, labels="{'LABEL1': 'value1', 'LABEL2': 'value2'}"

validate_ip_addrs : True
For parameters which accept IP addresses as input, IP address validation will be performed. To disable, set this to False
binds

Files/directories to bind mount. Each bind mount should be passed in the format <host_path>:<container_path>:<read_only>, where <read_only> is one of rw (for read-write access) or ro (for read-only access). Optionally, the read-only information can be left off the end and the bind mount will be assumed to be read-write. Examples 2 and 3 below are equivalent.

Example 1: binds=/srv/www:/var/www:ro

Example 2: binds=/srv/www:/var/www:rw

Example 3: binds=/srv/www:/var/www

port_bindings

Bind exposed ports which were exposed using the ports argument to dockerng.create. These should be passed in the same way as the --publish argument to the docker run CLI command:

  • ip:hostPort:containerPort - Bind a specific IP and port on the host to a specific port within the container.
  • ip::containerPort - Bind a specific IP and an ephemeral port to a specific port within the container.
  • hostPort:containerPort - Bind a specific port on all of the host's interfaces to a specific port within the container.
  • containerPort - Bind an ephemeral port on all of the host's interfaces to a specific port within the container.

Multiple bindings can be separated by commas, or passed as a Python list. The below two examples are equivalent:

Example 1: port_bindings="5000:5000,2123:2123/udp,8080"

Example 2: port_bindings="['5000:5000', '2123:2123/udp', '8080']"

注解

When configuring bindings for UDP ports, the protocol must be passed in the containerPort value, as seen in the examples above.

lxc_conf

Additional LXC configuration parameters to set before starting the container.

Example: lxc_conf="{lxc.utsname: docker}"

注解

These LXC configuration parameters will only have the desired effect if the container is using the LXC execution driver, which has not been the default for some time.

security_opt

Security configuration for MLS systems such as SELinux and AppArmor.

Example 1: security_opt="apparmor:unconfined"

Example 2: security_opt=["apparmor:unconfined"] security_opt=["apparmor:unconfined", "param2:value2"]

publish_all_ports : False

Allocates a random host port for each port exposed using the ports argument to dockerng.create.

Example: publish_all_ports=True

links

Link this container to another. Links should be specified in the format <container_name_or_id>:<link_alias>. Multiple links can be passed, ether as a comma separated list or a Python list.

Example 1: links=mycontainer:myalias, links=web1:link1,web2:link2

Example 2: links="['mycontainer:myalias']" links="['web1:link1', 'web2:link2']"

dns

List of DNS nameservers. Can be passed as a comma-separated list or a Python list.

Example: dns=8.8.8.8,8.8.4.4 or dns="[8.8.8.8, 8.8.4.4]"

注解

To skip IP address validation, use validate_ip_addrs=False

dns_search

List of DNS search domains. Can be passed as a comma-separated list or a Python list.

Example: dns_search=foo1.domain.tld,foo2.domain.tld or dns_search="[foo1.domain.tld, foo2.domain.tld]"

volumes_from

Container names or IDs from which the container will get volumes. Can be passed as a comma-separated list or a Python list.

Example: volumes_from=foo, volumes_from=foo,bar, volumes_from="[foo, bar]"

network_mode : bridge

One of the following:

  • bridge - Creates a new network stack for the container on the docker bridge

  • null - No networking (equivalent of the Docker CLI argument --net=none)

  • container:<name_or_id> - Reuses another container's network stack

  • host - Use the host's network stack inside the container

    警告

    Using host mode gives the container full access to the hosts system's services (such as D-bus), and is therefore considered insecure.

Example: network_mode=null, network_mode=container:web1

restart_policy

Set a restart policy for the container. Must be passed as a string in the format policy[:retry_count] where policy is one of always or on-failure, and retry_count is an optional limit to the number of retries. The retry count is ignored when using the always restart policy.

Example 1: restart_policy=on-failure:5

Example 2: restart_policy=always

cap_add

List of capabilities to add within the container. Can be passed as a comma-separated list or a Python list. Requires Docker 1.2.0 or newer.

Example: cap_add=SYS_ADMIN,MKNOD, cap_add="[SYS_ADMIN, MKNOD]"

cap_drop

List of capabilities to drop within the container. Can be passed as a comma-separated string or a Python list. Requires Docker 1.2.0 or newer.

Example: cap_drop=SYS_ADMIN,MKNOD, cap_drop="[SYS_ADMIN, MKNOD]"

extra_hosts

Additional hosts to add to the container's /etc/hosts file. Can be passed as a comma-separated list or a Python list. Requires Docker 1.3.0 or newer.

Example: extra_hosts=web1:10.9.8.7,web2:10.9.8.8

注解

To skip IP address validation, use validate_ip_addrs=False

pid_mode

Set to host to use the host container's PID namespace within the container. Requires Docker 1.5.0 or newer.

Example: pid_mode=host

RETURN DATA

A dictionary containing the following keys:

  • Id - ID of the newly-created container
  • Name - Name of the newly-created container

CLI Example:

# Create a data-only container
salt myminion dockerng.create myuser/mycontainer volumes="/mnt/vol1,/mnt/vol2"
# Create a CentOS 7 container that will stay running once started
salt myminion dockerng.create centos:7 name=mycent7 interactive=True tty=True command=bash
salt.modules.dockerng.create_network(name, driver=None)

Create a new network

network_id
ID of network
driver
Driver of the network

CLI Example:

salt myminion dockerng.create_network web_network driver=bridge
salt.modules.dockerng.create_volume(name, driver=None, driver_opts=None)

Create a new volume

2015.8.4 新版功能.

name
name of volume
driver
Driver of the volume
driver_opts
Options for the driver volume

CLI Example:

salt myminion dockerng.create_volume my_volume driver=local
salt.modules.dockerng.dangling(prune=False, force=False)

Return top-level images (those on which no other images depend) which do not have a tag assigned to them. These include:

  • Images which were once tagged but were later untagged, such as those which were superseded by committing a new copy of an existing tagged image.
  • Images which were loaded using docker.load (or the docker load Docker CLI command), but not tagged.
prune : False
Remove these images
force : False
If True, and if prune=True, then forcibly remove these images.

RETURN DATA

If prune=False, the return data will be a list of dangling image IDs.

If prune=True, the return data will be a dictionary with each key being the ID of the dangling image, and the following information for each image:

  • Comment - Any error encountered when trying to prune a dangling image

    (Only present if prune failed)

  • Removed - A boolean (True if prune was successful, False if not)

CLI Example:

salt myminion dockerng.dangling
salt myminion dockerng.dangling prune=True
salt.modules.dockerng.depends(name)

Returns the containers and images, if any, which depend on the given image

name
Name or ID of image

RETURN DATA

A dictionary containing the following keys:

  • Containers - A list of containers which depend on the specified image
  • Images - A list of IDs of images which depend on the specified image

CLI Example:

salt myminion dockerng.depends myimage
salt myminion dockerng.depends 0123456789ab
salt.modules.dockerng.diff(name, *args, **kwargs)

Get information on changes made to container's filesystem since it was created. Equivalent to running the docker diff Docker CLI command.

name
Container name or ID

RETURN DATA

A dictionary containing any of the following keys:

  • Added - A list of paths that were added.
  • Changed - A list of paths that were changed.
  • Deleted - A list of paths that were deleted.

These keys will only be present if there were changes, so if the container has no differences the return dict will be empty.

CLI Example:

salt myminion dockerng.diff mycontainer
salt.modules.dockerng.disconnect_container_from_network(container, network_id)

Disconnect container from network.

container
Container name or ID
network_id
ID of network

CLI Example:

salt myminion dockerng.disconnect_container_from_network web-1 1f9d2454d0872b68dd9e8744c6e7a4c66b86f10abaccc21e14f7f014f729b2bc
salt.modules.dockerng.exists(name)

Check if a given container exists

name
Container name or ID

RETURN DATA

A boolean (True if the container exists, otherwise False)

CLI Example:

salt myminion dockerng.exists mycontainer
salt.modules.dockerng.export(name, *args, **kwargs)

Exports a container to a tar archive. It can also optionally compress that tar archive, and push it up to the Master.

name
Container name or ID
path
Absolute path on the Minion where the container will be exported
overwrite : False
Unless this option is set to True, then if a file exists at the location specified by the path argument, an error will be raised.
makedirs : False
If True, then if the parent directory of the file specified by the path argument does not exist, Salt will attempt to create it.
compression : None

Can be set to any of the following:

  • gzip or gz for gzip compression
  • bzip2 or bz2 for bzip2 compression
  • xz or lzma for XZ compression (requires xz-utils, as well as the lzma module from Python 3.3, available in Python 2 and Python 3.0-3.2 as backports.lzma)

This parameter can be omitted and Salt will attempt to determine the compression type by examining the filename passed in the path parameter.

push : False

If True, the container will be pushed to the master using cp.push.

注解

This requires file_recv to be set to True on the Master.

RETURN DATA

A dictionary will containing the following keys:

  • Path - Path of the file that was exported

  • Push - Reports whether or not the file was successfully pushed to the Master

    (Only present if push=True)

  • Size - Size of the file, in bytes

  • Size_Human - Size of the file, in human-readable units

  • Time_Elapsed - Time in seconds taken to perform the export

CLI Examples:

salt myminion dockerng.export mycontainer /tmp/mycontainer.tar
salt myminion dockerng.export mycontainer /tmp/mycontainer.tar.xz push=True
salt.modules.dockerng.history(name, quiet=False)

Return the history for an image. Equivalent to running the docker history Docker CLI command.

name
Container name or ID
quiet : False

If True, the return data will simply be a list of the commands run to build the container.

$ salt myminion dockerng.history nginx:latest quiet=True
myminion:
    - FROM scratch
    - ADD file:ef063ed0ae9579362871b9f23d2bc0781ef7cd4de6ac822052cf6c9c5a12b1e2 in /
    - CMD [/bin/bash]
    - MAINTAINER NGINX Docker Maintainers "docker-maint@nginx.com"
    - apt-key adv --keyserver pgp.mit.edu --recv-keys 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62
    - echo "deb http://nginx.org/packages/mainline/debian/ wheezy nginx" >> /etc/apt/sources.list
    - ENV NGINX_VERSION=1.7.10-1~wheezy
    - apt-get update &&     apt-get install -y ca-certificates nginx=${NGINX_VERSION} &&     rm -rf /var/lib/apt/lists/*
    - ln -sf /dev/stdout /var/log/nginx/access.log
    - ln -sf /dev/stderr /var/log/nginx/error.log
    - VOLUME [/var/cache/nginx]
    - EXPOSE map[80/tcp:{} 443/tcp:{}]
    - CMD [nginx -g daemon off;]
            https://github.com/saltstack/salt/pull/22421

RETURN DATA

If quiet=False, the return value will be a list of dictionaries containing information about each step taken to build the image. The keys in each step include the following:

  • Command - The command executed in this build step
  • Id - Layer ID
  • Size - Cumulative image size, in bytes
  • Size_Human - Cumulative image size, in human-readable units
  • Tags - Tag(s) assigned to this layer
  • Time_Created_Epoch - Time this build step was completed (Epoch time)
  • Time_Created_Local - Time this build step was completed (Minion's local timezone)

CLI Example:

salt myminion dockerng.exists mycontainer
salt.modules.dockerng.images(verbose=False, **kwargs)

Returns information about the Docker images on the Minion. Equivalent to running the docker images Docker CLI command.

all : False
If True, untagged images will also be returned
verbose : False
If True, a docker inspect will be run on each image returned.

RETURN DATA

A dictionary with each key being an image ID, and each value some general info about that image (time created, size, tags associated with the image, etc.)

CLI Example:

salt myminion dockerng.images
salt myminion dockerng.images all=True
salt.modules.dockerng.import(source, image, api_response=False)

Imports content from a local tarball or a URL as a new docker image

source
Content to import (URL or absolute path to a tarball). URL can be a file on the Salt fileserver (i.e. salt://path/to/rootfs/tarball.tar.xz. To import a file from a saltenv other than base (e.g. dev), pass it at the end of the URL (ex. salt://path/to/rootfs/tarball.tar.xz?saltenv=dev).
image
Image to be created by the import, in repo:tag notation. If just the repository name is passed, a tag name of latest will be assumed.
api_response : False
If True an api_response key will be present in the return data, containing the raw output from the Docker API.

RETURN DATA

A dictionary containing the following keys:

  • Id - ID of the newly-created image
  • Image - Name of the newly-created image
  • Time_Elapsed - Time in seconds taken to perform the commit

CLI Example:

salt myminion dockerng.import /tmp/cent7-minimal.tar.xz myuser/centos
salt myminion dockerng.import /tmp/cent7-minimal.tar.xz myuser/centos:7
salt myminion dockerng.import salt://dockerimages/cent7-minimal.tar.xz myuser/centos:7
salt.modules.dockerng.info(*args, **kwargs)

Returns a dictionary of system-wide information. Equivalent to running the docker info Docker CLI command.

CLI Example:

salt myminion dockerng.info
salt.modules.dockerng.inspect(name)

This is a generic container/image inspecton function. It will first attempt to get container information for the passed name/ID using docker.inspect_container, and then will try to get image information for the passed name/ID using docker.inspect_image. If it is already known that the name/ID is an image, it is slightly more efficient to use docker.inspect_image.

name
Container/image name or ID

RETURN DATA

A dictionary of container/image information

CLI Example:

salt myminion dockerng.inspect mycontainer
salt myminion dockerng.inspect busybox
salt.modules.dockerng.inspect_container(name, *args, **kwargs)

Retrieves container information. Equivalent to running the docker inspect Docker CLI command, but will only look for container information.

name
Container name or ID

RETURN DATA

A dictionary of container information

CLI Example:

salt myminion dockerng.inspect_container mycontainer
salt myminion dockerng.inspect_container 0123456789ab
salt.modules.dockerng.inspect_image(name)

Retrieves image information. Equivalent to running the docker inspect Docker CLI command, but will only look for image information.

注解

To inspect an image, it must have been pulled from a registry or built locally. Images on a Docker registry which have not been pulled cannot be inspected.

name
Image name or ID

RETURN DATA

A dictionary of image information

CLI Examples:

salt myminion dockerng.inspect_image busybox
salt myminion dockerng.inspect_image centos:6
salt myminion dockerng.inspect_image 0123456789ab
salt.modules.dockerng.inspect_network(network_id)

Inspect Network

network_id
ID of network

CLI Example:

salt myminion dockerng.inspect_network 1f9d2454d0872b68dd9e8744c6e7a4c66b86f10abaccc21e14f7f014f729b2bc
salt.modules.dockerng.inspect_volume(name)

Inspect Volume

2015.8.4 新版功能.

name
Name of volume

CLI Example:

salt myminion dockerng.inspect_volume my_volume
salt.modules.dockerng.kill(*args, **kwargs)

Kill all processes in a running container instead of performing a graceful shutdown

name
Container name or ID

RETURN DATA

A dictionary will be returned, containing the following keys:

  • status - A dictionary showing the prior state of the container as well as the new state
  • result - A boolean noting whether or not the action was successful
  • comment - Only present if the container cannot be killed

CLI Example:

salt myminion dockerng.kill mycontainer
salt.modules.dockerng.layers(name)

Returns a list of the IDs of layers belonging to the specified image, with the top-most layer (the one correspnding to the passed name) appearing last.

name
Image name or ID

CLI Example:

salt myminion dockerng.layers centos:7
salt.modules.dockerng.list_containers(**kwargs)

Returns a list of containers by name. This is different from dockerng.ps in that dockerng.ps returns its results organized by container ID.

all : False
If True, stopped containers will be included in return data

CLI Example:

salt myminion dockerng.inspect_image <image>
salt.modules.dockerng.list_tags()

Returns a list of tagged images

CLI Example:

salt myminion dockerng.list_tags
salt.modules.dockerng.load(path, image=None)

Load a tar archive that was created using dockerng.save (or via the Docker CLI using docker save).

path
Path to docker tar archive. Path can be a file on the Minion, or the URL of a file on the Salt fileserver (i.e. salt://path/to/docker/saved/image.tar). To load a file from a saltenv other than base (e.g. dev), pass it at the end of the URL (ex. salt://path/to/rootfs/tarball.tar.xz?saltenv=dev).
image : None
If specified, the topmost layer of the newly-loaded image will be tagged with the specified repo and tag using dockerng.tag. The image name should be specified in repo:tag notation. If just the repository name is passed, a tag name of latest will be assumed.

RETURN DATA

A dictionary will be returned, containing the following keys:

  • Path - Path of the file that was saved

  • Layers - A list containing the IDs of the layers which were loaded. Any layers in the file that was loaded, which were already present on the Minion, will not be included.

  • Image - Name of tag applied to topmost layer

    (Only present if tag was specified and tagging was successful)

  • Time_Elapsed - Time in seconds taken to load the file

  • Warning - Message describing any problems encountered in attemp to tag the topmost layer

    (Only present if tag was specified and tagging failed)

CLI Example:

salt myminion dockerng.load /path/to/image.tar
salt myminion dockerng.load salt://path/to/docker/saved/image.tar image=myuser/myimage:mytag
salt.modules.dockerng.logs(name)

Returns the logs for the container. Equivalent to running the docker logs Docker CLI command.

name
Container name or ID

CLI Example:

salt myminion dockerng.logs mycontainer
salt.modules.dockerng.networks(names=None, ids=None)

List existing networks

names
Filter by name
ids
Filter by id

CLI Example:

salt myminion dockerng.networks names="['network-web']"
salt myminion dockerng.networks ids="['1f9d2454d0872b68dd9e8744c6e7a4c66b86f10abaccc21e14f7f014f729b2bc']"
salt.modules.dockerng.pause(*args, **kwargs)

Pauses a container

name
Container name or ID

RETURN DATA

A dictionary will be returned, containing the following keys:

  • status - A dictionary showing the prior state of the container as well as the new state
  • result - A boolean noting whether or not the action was successful
  • comment - Only present if the container cannot be paused

CLI Example:

salt myminion dockerng.pause mycontainer
salt.modules.dockerng.pid(name, *args, **kwargs)

Returns the PID of a container

name
Container name or ID

CLI Example:

salt myminion dockerng.pid mycontainer
salt myminion dockerng.pid 0123456789ab
salt.modules.dockerng.port(name, *args, **kwargs)

Returns port mapping information for a given container. Equivalent to running the docker port Docker CLI command.

name
Container name or ID
private_port : None

If specified, get information for that specific port. Can be specified either as a port number (i.e. 5000), or as a port number plus the protocol (i.e. 5000/udp).

If this argument is omitted, all port mappings will be returned.

RETURN DATA

A dictionary of port mappings, with the keys being the port and the values being the mapping(s) for that port.

CLI Examples:

salt myminion dockerng.port mycontainer
salt myminion dockerng.port mycontainer 5000
salt myminion dockerng.port mycontainer 5000/udp
salt.modules.dockerng.ps(filters=None, **kwargs)

Returns information about the Docker containers on the Minion. Equivalent to running the docker ps Docker CLI command.

all : False
If True, stopped containers will also be returned
host: False
If True, local host's network topology will be included
verbose : False
If True, a docker inspect will be run on each container returned.
filters: None

A dictionary of filters to be processed on the container list. Available filters:

  • exited (int): Only containers with specified exit code
  • status (str): One of restarting, running, paused, exited
  • label (str): format either "key" or "key=value"

RETURN DATA

A dictionary with each key being an container ID, and each value some general info about that container (time created, name, command, etc.)

CLI Example:

salt myminion dockerng.ps
salt myminion dockerng.ps all=True
salt myminion dockerng.ps filters="{'label': 'role=web'}"
salt.modules.dockerng.pull(image, insecure_registry=False, api_response=False, client_timeout=60)

Pulls an image from a Docker registry. See the documentation at the top of this page to configure authenticated access.

image
Image to be pulled, in repo:tag notation. If just the repository name is passed, a tag name of latest will be assumed.
insecure_registry : False
If True, the Docker client will permit the use of insecure (non-HTTPS) registries.
api_response : False

If True, an API_Response key will be present in the return data, containing the raw output from the Docker API.

注解

This may result in a lot of additional return data, especially for larger images.

client_timeout
Timeout in seconds for the Docker client. This is not a timeout for this function, but for receiving a response from the API.

RETURN DATA

A dictionary will be returned, containing the following keys:

  • Layers - A dictionary containing one or more of the following keys:
    • Already_Pulled - Layers that that were already present on the Minion
    • Pulled - Layers that that were pulled
  • Status - A string containing a summary of the pull action (usually a message saying that an image was downloaded, or that it was up to date).

  • Time_Elapsed - Time in seconds taken to perform the pull

CLI Example:

salt myminion dockerng.pull centos
salt myminion dockerng.pull centos:6
salt.modules.dockerng.push(image, insecure_registry=False, api_response=False, client_timeout=60)

在 2015.8.4 版更改: The Id and Image keys are no longer present in the return data. This is due to changes in the Docker Remote API.

Pushes an image to a Docker registry. See the documentation at top of this page to configure authenticated access.

image

Image to be pushed, in repo:tag notation.

在 2015.8.4 版更改: If just the repository name is passed, then all tagged images for the specified repo will be pushed. In prior releases, a tag of latest was assumed if the tag was omitted.

insecure_registry : False
If True, the Docker client will permit the use of insecure (non-HTTPS) registries.
api_response : False
If True, an API_Response key will be present in the return data, containing the raw output from the Docker API.
client_timeout
Timeout in seconds for the Docker client. This is not a timeout for this function, but for receiving a response from the API.

RETURN DATA

A dictionary will be returned, containing the following keys:

  • Layers - A dictionary containing one or more of the following keys:
    • Already_Pushed - Layers that that were already present on the Minion
    • Pushed - Layers that that were pushed
  • Time_Elapsed - Time in seconds taken to perform the push

CLI Example:

salt myminion dockerng.push myuser/mycontainer
salt myminion dockerng.push myuser/mycontainer:mytag
salt.modules.dockerng.remove_network(network_id)

Remove a network

network_id
ID of network

CLI Example:

salt myminion dockerng.remove_network 1f9d2454d0872b68dd9e8744c6e7a4c66b86f10abaccc21e14f7f014f729b2bc
salt.modules.dockerng.remove_volume(name)

Remove a volume

2015.8.4 新版功能.

name
Name of volume

CLI Example:

salt myminion dockerng.remove_volume my_volume
salt.modules.dockerng.restart(name, *args, **kwargs)

Restarts a container

name
Container name or ID
timeout : 10
Timeout in seconds after which the container will be killed (if it has not yet gracefully shut down)

RETURN DATA

A dictionary will be returned, containing the following keys:

  • status - A dictionary showing the prior state of the container as well as the new state
  • result - A boolean noting whether or not the action was successful
  • restarted - If restart was successful, this key will be present and will be set to True.

CLI Examples:

salt myminion dockerng.restart mycontainer
salt myminion dockerng.restart mycontainer timeout=20
salt.modules.dockerng.retcode(name, cmd, exec_driver=None, stdin=None, python_shell=True, output_loglevel='debug', use_vt=False, ignore_retcode=False, keep_env=None)

Run cmd.retcode within a container

name
Container name or ID in which to run the command
cmd
Command to run
exec_driver : None
If not passed, the execution driver will be detected as described above.
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to quiet to suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console.
keep_env : None
If not passed, only a sane default PATH environment variable will be set. If True, all environment variables from the container's host will be kept. Otherwise, a comma-separated list (or Python list) of environment variable names can be passed, and those environment variables will be kept.

CLI Example:

salt myminion dockerng.retcode mycontainer 'ls -l /etc'
salt.modules.dockerng.rm(*args, **kwargs)

Removes a container

name
Container name or ID
force : False
If True, the container will be killed first before removal, as the Docker API will not permit a running container to be removed. This option is set to False by default to prevent accidental removal of a running container.
volumes : False
Also remove volumes associated with container

RETURN DATA

A list of the IDs of containers which were removed

CLI Example:

salt myminion dockerng.rm mycontainer
salt myminion dockerng.rm mycontainer force=True
salt.modules.dockerng.rmi(*names, **kwargs)

Removes an image

name
Name (in repo:tag notation) or ID of image.
force : False
If True, the image will be removed even if the Minion has containers created from that image
prune : True
If True, untagged parent image layers will be removed as well, set this to False to keep them.

RETURN DATA

A dictionary will be returned, containing the following two keys:

  • Layers - A list of the IDs of image layers that were removed
  • Tags - A list of the tags that were removed
  • Errors - A list of any errors that were encountered

CLI Examples:

salt myminion dockerng.rmi busybox
salt myminion dockerng.rmi busybox force=True
salt myminion dockerng.rmi foo bar baz
salt.modules.dockerng.run(name, cmd, exec_driver=None, stdin=None, python_shell=True, output_loglevel='debug', use_vt=False, ignore_retcode=False, keep_env=None)

Run cmd.run within a container

name
Container name or ID in which to run the command
cmd
Command to run
exec_driver : None
If not passed, the execution driver will be detected as described above.
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to quiet to suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console.
keep_env : None
If not passed, only a sane default PATH environment variable will be set. If True, all environment variables from the container's host will be kept. Otherwise, a comma-separated list (or Python list) of environment variable names can be passed, and those environment variables will be kept.

CLI Example:

salt myminion dockerng.run mycontainer 'ls -l /etc'
salt.modules.dockerng.run_all(name, cmd, exec_driver=None, stdin=None, python_shell=True, output_loglevel='debug', use_vt=False, ignore_retcode=False, keep_env=None)

Run cmd.run_all within a container

注解

While the command is run within the container, it is initiated from the host. Therefore, the PID in the return dict is from the host, not from the container.

name
Container name or ID in which to run the command
cmd
Command to run
exec_driver : None
If not passed, the execution driver will be detected as described above.
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to quiet to suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console.
keep_env : None
If not passed, only a sane default PATH environment variable will be set. If True, all environment variables from the container's host will be kept. Otherwise, a comma-separated list (or Python list) of environment variable names can be passed, and those environment variables will be kept.

CLI Example:

salt myminion dockerng.run_all mycontainer 'ls -l /etc'
salt.modules.dockerng.run_stderr(name, cmd, exec_driver=None, stdin=None, python_shell=True, output_loglevel='debug', use_vt=False, ignore_retcode=False, keep_env=None)

Run cmd.run_stderr within a container

name
Container name or ID in which to run the command
cmd
Command to run
exec_driver : None
If not passed, the execution driver will be detected as described above.
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to quiet to suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console.
keep_env : None
If not passed, only a sane default PATH environment variable will be set. If True, all environment variables from the container's host will be kept. Otherwise, a comma-separated list (or Python list) of environment variable names can be passed, and those environment variables will be kept.

CLI Example:

salt myminion dockerng.run_stderr mycontainer 'ls -l /etc'
salt.modules.dockerng.run_stdout(name, cmd, exec_driver=None, stdin=None, python_shell=True, output_loglevel='debug', use_vt=False, ignore_retcode=False, keep_env=None)

Run cmd.run_stdout within a container

name
Container name or ID in which to run the command
cmd
Command to run
exec_driver : None
If not passed, the execution driver will be detected as described above.
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to quiet to suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console.
keep_env : None
If not passed, only a sane default PATH environment variable will be set. If True, all environment variables from the container's host will be kept. Otherwise, a comma-separated list (or Python list) of environment variable names can be passed, and those environment variables will be kept.

CLI Example:

salt myminion dockerng.run_stdout mycontainer 'ls -l /etc'
salt.modules.dockerng.save(name, path, overwrite=False, makedirs=False, compression=None, **kwargs)

Saves an image and to a file on the minion. Equivalent to running the docker save Docker CLI command, but unlike docker save this will also work on named images instead of just images IDs.

name
Name or ID of image. Specify a specific tag by using the repo:tag notation.
path
Absolute path on the Minion where the image will be exported
overwrite : False
Unless this option is set to True, then if the destination file exists an error will be raised.
makedirs : False
If True, then if the parent directory of the file specified by the path argument does not exist, Salt will attempt to create it.
compression : None

Can be set to any of the following:

  • gzip or gz for gzip compression
  • bzip2 or bz2 for bzip2 compression
  • xz or lzma for XZ compression (requires xz-utils, as well as the lzma module from Python 3.3, available in Python 2 and Python 3.0-3.2 as backports.lzma)

This parameter can be omitted and Salt will attempt to determine the compression type by examining the filename passed in the path parameter.

注解

Since the Docker API does not support docker save, compression will be a bit slower with this function than with docker.export since the image(s) will first be saved and then the compression done afterwards.

push : False

If True, the container will be pushed to the master using cp.push.

注解

This requires file_recv to be set to True on the Master.

RETURN DATA

A dictionary will be returned, containing the following keys:

  • Path - Path of the file that was saved

  • Push - Reports whether or not the file was successfully pushed to the Master

    (Only present if push=True)

  • Size - Size of the file, in bytes

  • Size_Human - Size of the file, in human-readable units

  • Time_Elapsed - Time in seconds taken to perform the save

CLI Examples:

salt myminion dockerng.save centos:7 /tmp/cent7.tar
salt myminion dockerng.save 0123456789ab cdef01234567 /tmp/saved.tar
salt.modules.dockerng.script(name, source, saltenv='base', args=None, template=None, exec_driver=None, stdin=None, python_shell=True, output_loglevel='debug', ignore_retcode=False, use_vt=False, keep_env=None)

Run cmd.script within a container

注解

While the command is run within the container, it is initiated from the host. Therefore, the PID in the return dict is from the host, not from the container.

name
Container name or ID
source
Path to the script. Can be a local path on the Minion or a remote file from the Salt fileserver.
args
A string containing additional command-line options to pass to the script.
template : None
Templating engine to use on the script before running.
exec_driver : None
If not passed, the execution driver will be detected as described above.
stdin : None
Standard input to be used for the script
output_loglevel : debug
Level at which to log the output from the script. Set to quiet to suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console.
keep_env : None
If not passed, only a sane default PATH environment variable will be set. If True, all environment variables from the container's host will be kept. Otherwise, a comma-separated list (or Python list) of environment variable names can be passed, and those environment variables will be kept.

CLI Example:

salt myminion dockerng.script mycontainer salt://docker_script.py
salt myminion dockerng.script mycontainer salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt myminion dockerng.script mycontainer salt://scripts/runme.sh stdin='one\ntwo\nthree\nfour\nfive\n' output_loglevel=quiet
salt.modules.dockerng.script_retcode(name, source, saltenv='base', args=None, template=None, exec_driver=None, stdin=None, python_shell=True, output_loglevel='debug', ignore_retcode=False, use_vt=False, keep_env=None)

Run cmd.script_retcode within a container

name
Container name or ID
source
Path to the script. Can be a local path on the Minion or a remote file from the Salt fileserver.
args
A string containing additional command-line options to pass to the script.
template : None
Templating engine to use on the script before running.
exec_driver : None
If not passed, the execution driver will be detected as described above.
stdin : None
Standard input to be used for the script
output_loglevel : debug
Level at which to log the output from the script. Set to quiet to suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console.
keep_env : None
If not passed, only a sane default PATH environment variable will be set. If True, all environment variables from the container's host will be kept. Otherwise, a comma-separated list (or Python list) of environment variable names can be passed, and those environment variables will be kept.

CLI Example:

salt myminion dockerng.script_retcode mycontainer salt://docker_script.py
salt myminion dockerng.script_retcode mycontainer salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt myminion dockerng.script_retcode mycontainer salt://scripts/runme.sh stdin='one\ntwo\nthree\nfour\nfive\n' output_loglevel=quiet
salt.modules.dockerng.search(name, official=False, trusted=False)

Searches the registry for an image

name
Search keyword
official : False
Limit results to official builds
trusted : False
Limit results to trusted builds

RETURN DATA

A dictionary with each key being the name of an image, and the following information for each image:

  • Description - Image description
  • Official - A boolean (True if an official build, False if not)
  • Stars - Number of stars the image has on the registry
  • Trusted - A boolean (True if a trusted build, False if not)

CLI Example:

salt myminion dockerng.search centos
salt myminion dockerng.search centos official=True
salt.modules.dockerng.signal(*args, **kwargs)

Send a signal to a container. Signals can be either strings or numbers, and are defined in the Standard Signals section of the signal(7) manpage. Run man 7 signal on a Linux host to browse this manpage.

name
Container name or ID
signal
Signal to send to container

RETURN DATA

If the signal was successfully sent, True will be returned. Otherwise, an error will be raised.

CLI Example:

salt myminion dockerng.signal mycontainer SIGHUP
salt.modules.dockerng.start(*args, **kwargs)

Start a container

name
Container name or ID

RETURN DATA

A dictionary will be returned, containing the following keys:

  • status - A dictionary showing the prior state of the container as well as the new state
  • result - A boolean noting whether or not the action was successful
  • comment - Only present if the container cannot be started

CLI Example:

salt myminion dockerng.start mycontainer
salt.modules.dockerng.state(name, *args, **kwargs)

Returns the state of the container

name
Container name or ID

RETURN DATA

A string representing the current state of the container (either running, paused, or stopped)

CLI Example:

salt myminion dockerng.state mycontainer
salt.modules.dockerng.stop(*args, **kwargs)

Stops a running container

name
Container name or ID
unpause : False
If True and the container is paused, it will be unpaused before attempting to stop the container.
timeout : 10
Timeout in seconds after which the container will be killed (if it has not yet gracefully shut down)

RETURN DATA

A dictionary will be returned, containing the following keys:

  • status - A dictionary showing the prior state of the container as well as the new state
  • result - A boolean noting whether or not the action was successful
  • comment - Only present if the container can not be stopped

CLI Examples:

salt myminion dockerng.stop mycontainer
salt myminion dockerng.stop mycontainer unpause=True
salt myminion dockerng.stop mycontainer timeout=20
salt.modules.dockerng.tag(name, image, force=False)

Tag an image into a repository and return True. If the tag was unsuccessful, an error will be raised.

name
ID of image
image
Tag to apply to the image, in repo:tag notation. If just the repository name is passed, a tag name of latest will be assumed.
force : False
Force apply tag

CLI Example:

salt myminion dockerng.tag 0123456789ab myrepo/mycontainer
salt myminion dockerng.tag 0123456789ab myrepo/mycontainer:mytag
salt.modules.dockerng.top(name, *args, **kwargs)

Runs the docker top command on a specific container

name
Container name or ID

CLI Example:

RETURN DATA

A list of dictionaries containing information about each process

salt myminion dockerng.top mycontainer
salt myminion dockerng.top 0123456789ab
salt.modules.dockerng.unpause(*args, **kwargs)

Unpauses a container

name
Container name or ID

RETURN DATA

A dictionary will be returned, containing the following keys:

  • status - A dictionary showing the prior state of the container as well as the new state
  • result - A boolean noting whether or not the action was successful
  • comment - Only present if the container can not be unpaused

CLI Example:

salt myminion dockerng.pause mycontainer
salt.modules.dockerng.version()

Returns a dictionary of Docker version information. Equivalent to running the docker version Docker CLI command.

CLI Example:

salt myminion dockerng.version
salt.modules.dockerng.volumes(filters=None)

List existing volumes

2015.8.4 新版功能.

filters
There is one available filter: dangling=true

CLI Example:

salt myminion dockerng.volumes filters="{'dangling': True}"
salt.modules.dockerng.wait(name)

Wait for the container to exit gracefully, and return its exit code

注解

This function will block until the container is stopped.

name
Container name or ID

RETURN DATA

A dictionary will be returned, containing the following keys:

  • status - A dictionary showing the prior state of the container as well as the new state
  • result - A boolean noting whether or not the action was successful
  • exit_status - Exit status for the container
  • comment - Only present if the container is already stopped

CLI Example:

salt myminion dockerng.wait mycontainer