github.com/tompao/docker@v1.9.1/docs/reference/commandline/run.md (about)

     1  <!--[metadata]>
     2  +++
     3  title = "run"
     4  description = "The run command description and usage"
     5  keywords = ["run, command, container"]
     6  [menu.main]
     7  parent = "smn_cli"
     8  +++
     9  <![end-metadata]-->
    10  
    11  # run
    12  
    13      Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
    14  
    15      Run a command in a new container
    16  
    17        -a, --attach=[]               Attach to STDIN, STDOUT or STDERR
    18        --add-host=[]                 Add a custom host-to-IP mapping (host:ip)
    19        --blkio-weight=0              Block IO weight (relative weight)
    20        --cpu-shares=0                CPU shares (relative weight)
    21        --cap-add=[]                  Add Linux capabilities
    22        --cap-drop=[]                 Drop Linux capabilities
    23        --cgroup-parent=""            Optional parent cgroup for the container
    24        --cidfile=""                  Write the container ID to the file
    25        --cpu-period=0                Limit CPU CFS (Completely Fair Scheduler) period
    26        --cpu-quota=0                 Limit CPU CFS (Completely Fair Scheduler) quota
    27        --cpuset-cpus=""              CPUs in which to allow execution (0-3, 0,1)
    28        --cpuset-mems=""              Memory nodes (MEMs) in which to allow execution (0-3, 0,1)
    29        -d, --detach=false            Run container in background and print container ID
    30        --device=[]                   Add a host device to the container
    31        --disable-content-trust=true  Skip image verification
    32        --dns=[]                      Set custom DNS servers
    33        --dns-opt=[]                  Set custom DNS options
    34        --dns-search=[]               Set custom DNS search domains
    35        -e, --env=[]                  Set environment variables
    36        --entrypoint=""               Overwrite the default ENTRYPOINT of the image
    37        --env-file=[]                 Read in a file of environment variables
    38        --expose=[]                   Expose a port or a range of ports
    39        --group-add=[]                Add additional groups to run as
    40        -h, --hostname=""             Container host name
    41        --help=false                  Print usage
    42        -i, --interactive=false       Keep STDIN open even if not attached
    43        --ipc=""                      IPC namespace to use
    44        --kernel-memory=""            Kernel memory limit
    45        -l, --label=[]                Set metadata on the container (e.g., --label=com.example.key=value)
    46        --label-file=[]               Read in a file of labels (EOL delimited)
    47        --link=[]                     Add link to another container
    48        --log-driver=""               Logging driver for container
    49        --log-opt=[]                  Log driver specific options
    50        --lxc-conf=[]                 Add custom lxc options
    51        -m, --memory=""               Memory limit
    52        --mac-address=""              Container MAC address (e.g. 92:d0:c6:0a:29:33)
    53        --memory-reservation=""       Memory soft limit
    54        --memory-swap=""              Total memory (memory + swap), '-1' to disable swap
    55        --memory-swappiness=""        Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100.
    56        --name=""                     Assign a name to the container
    57        --net="bridge"                Connects a container to a network
    58                                      'bridge': creates a new network stack for the container on the docker bridge
    59                                      'none': no networking for this container
    60                                      'container:<name|id>': reuses another container network stack
    61                                      'host': use the host network stack inside the container
    62                                      'NETWORK': connects the container to user-created network using `docker network create` command
    63        --oom-kill-disable=false      Whether to disable OOM Killer for the container or not
    64        -P, --publish-all=false       Publish all exposed ports to random ports
    65        -p, --publish=[]              Publish a container's port(s) to the host
    66        --pid=""                      PID namespace to use
    67        --privileged=false            Give extended privileges to this container
    68        --read-only=false             Mount the container's root filesystem as read only
    69        --restart="no"                Restart policy (no, on-failure[:max-retry], always, unless-stopped)
    70        --rm=false                    Automatically remove the container when it exits
    71        --security-opt=[]             Security Options
    72        --sig-proxy=true              Proxy received signals to the process
    73        --stop-signal="SIGTERM"       Signal to stop a container
    74        -t, --tty=false               Allocate a pseudo-TTY
    75        -u, --user=""                 Username or UID (format: <name|uid>[:<group|gid>])
    76        --ulimit=[]                   Ulimit options
    77        --uts=""                      UTS namespace to use
    78        -v, --volume=[]               Bind mount a volume
    79        --volumes-from=[]             Mount volumes from the specified container(s)
    80        -w, --workdir=""              Working directory inside the container
    81  
    82  The `docker run` command first `creates` a writeable container layer over the
    83  specified image, and then `starts` it using the specified command. That is,
    84  `docker run` is equivalent to the API `/containers/create` then
    85  `/containers/(id)/start`. A stopped container can be restarted with all its
    86  previous changes intact using `docker start`. See `docker ps -a` to view a list
    87  of all containers.
    88  
    89  The `docker run` command can be used in combination with `docker commit` to
    90  [*change the command that a container runs*](commit.md). There is additional detailed information about `docker run` in the [Docker run reference](../run.md).
    91  
    92  For information on connecting a container to a network, see the ["*Docker network overview*"](../../userguide/networking/index.md).
    93  
    94  ## Examples
    95  
    96  ### Assign name and allocate psuedo-TTY (--name, -it)
    97  
    98      $ docker run --name test -it debian
    99      root@d6c0fe130dba:/# exit 13
   100      $ echo $?
   101      13
   102      $ docker ps -a | grep test
   103      d6c0fe130dba        debian:7            "/bin/bash"         26 seconds ago      Exited (13) 17 seconds ago                         test
   104  
   105  This example runs a container named `test` using the `debian:latest`
   106  image. The `-it` instructs Docker to allocate a pseudo-TTY connected to
   107  the container's stdin; creating an interactive `bash` shell in the container.
   108  In the example, the `bash` shell is quit by entering
   109  `exit 13`. This exit code is passed on to the caller of
   110  `docker run`, and is recorded in the `test` container's metadata.
   111  
   112  ### Capture container ID (--cidfile)
   113  
   114      $ docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"
   115  
   116  This will create a container and print `test` to the console. The `cidfile`
   117  flag makes Docker attempt to create a new file and write the container ID to it.
   118  If the file exists already, Docker will return an error. Docker will close this
   119  file when `docker run` exits.
   120  
   121  ### Full container capabilities (--privileged)
   122  
   123      $ docker run -t -i --rm ubuntu bash
   124      root@bc338942ef20:/# mount -t tmpfs none /mnt
   125      mount: permission denied
   126  
   127  This will *not* work, because by default, most potentially dangerous kernel
   128  capabilities are dropped; including `cap_sys_admin` (which is required to mount
   129  filesystems). However, the `--privileged` flag will allow it to run:
   130  
   131      $ docker run --privileged ubuntu bash
   132      root@50e3f57e16e6:/# mount -t tmpfs none /mnt
   133      root@50e3f57e16e6:/# df -h
   134      Filesystem      Size  Used Avail Use% Mounted on
   135      none            1.9G     0  1.9G   0% /mnt
   136  
   137  The `--privileged` flag gives *all* capabilities to the container, and it also
   138  lifts all the limitations enforced by the `device` cgroup controller. In other
   139  words, the container can then do almost everything that the host can do. This
   140  flag exists to allow special use-cases, like running Docker within Docker.
   141  
   142  ### Set working directory (-w)
   143  
   144      $ docker  run -w /path/to/dir/ -i -t  ubuntu pwd
   145  
   146  The `-w` lets the command being executed inside directory given, here
   147  `/path/to/dir/`. If the path does not exists it is created inside the container.
   148  
   149  ### Mount volume (-v, --read-only)
   150  
   151      $ docker  run  -v `pwd`:`pwd` -w `pwd` -i -t  ubuntu pwd
   152  
   153  The `-v` flag mounts the current working directory into the container. The `-w`
   154  lets the command being executed inside the current working directory, by
   155  changing into the directory to the value returned by `pwd`. So this
   156  combination executes the command using the container, but inside the
   157  current working directory.
   158  
   159      $ docker run -v /doesnt/exist:/foo -w /foo -i -t ubuntu bash
   160  
   161  When the host directory of a bind-mounted volume doesn't exist, Docker
   162  will automatically create this directory on the host for you. In the
   163  example above, Docker will create the `/doesnt/exist`
   164  folder before starting your container.
   165  
   166      $ docker run --read-only -v /icanwrite busybox touch /icanwrite here
   167  
   168  Volumes can be used in combination with `--read-only` to control where
   169  a container writes files. The `--read-only` flag mounts the container's root
   170  filesystem as read only prohibiting writes to locations other than the
   171  specified volumes for the container.
   172  
   173      $ docker run -t -i -v /var/run/docker.sock:/var/run/docker.sock -v ./static-docker:/usr/bin/docker busybox sh
   174  
   175  By bind-mounting the docker unix socket and statically linked docker
   176  binary (such as that provided by [https://get.docker.com](
   177  https://get.docker.com)), you give the container the full access to create and
   178  manipulate the host's Docker daemon.
   179  
   180  ### Publish or expose port (-p, --expose)
   181  
   182      $ docker run -p 127.0.0.1:80:8080 ubuntu bash
   183  
   184  This binds port `8080` of the container to port `80` on `127.0.0.1` of the host
   185  machine. The [Docker User
   186  Guide](../../userguide/networking/default_network/dockerlinks.md)
   187  explains in detail how to manipulate ports in Docker.
   188  
   189      $ docker run --expose 80 ubuntu bash
   190  
   191  This exposes port `80` of the container without publishing the port to the host
   192  system's interfaces.
   193  
   194  ### Set environment variables (-e, --env, --env-file)
   195  
   196      $ docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bash
   197  
   198  This sets environmental variables in the container. For illustration all three
   199  flags are shown here. Where `-e`, `--env` take an environment variable and
   200  value, or if no `=` is provided, then that variable's current value is passed
   201  through (i.e. `$MYVAR1` from the host is set to `$MYVAR1` in the container).
   202  When no `=` is provided and that variable is not defined in the client's
   203  environment then that variable will be removed from the container's list of
   204  environment variables.
   205  All three flags, `-e`, `--env` and `--env-file` can be repeated.
   206  
   207  Regardless of the order of these three flags, the `--env-file` are processed
   208  first, and then `-e`, `--env` flags. This way, the `-e` or `--env` will
   209  override variables as needed.
   210  
   211      $ cat ./env.list
   212      TEST_FOO=BAR
   213      $ docker run --env TEST_FOO="This is a test" --env-file ./env.list busybox env | grep TEST_FOO
   214      TEST_FOO=This is a test
   215  
   216  The `--env-file` flag takes a filename as an argument and expects each line
   217  to be in the `VAR=VAL` format, mimicking the argument passed to `--env`. Comment
   218  lines need only be prefixed with `#`
   219  
   220  An example of a file passed with `--env-file`
   221  
   222      $ cat ./env.list
   223      TEST_FOO=BAR
   224  
   225      # this is a comment
   226      TEST_APP_DEST_HOST=10.10.0.127
   227      TEST_APP_DEST_PORT=8888
   228      _TEST_BAR=FOO
   229      TEST_APP_42=magic
   230      helloWorld=true
   231      123qwe=bar
   232      org.spring.config=something
   233  
   234      # pass through this variable from the caller
   235      TEST_PASSTHROUGH
   236      $ TEST_PASSTHROUGH=howdy docker run --env-file ./env.list busybox env
   237      PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
   238      HOSTNAME=5198e0745561
   239      TEST_FOO=BAR
   240      TEST_APP_DEST_HOST=10.10.0.127
   241      TEST_APP_DEST_PORT=8888
   242      _TEST_BAR=FOO
   243      TEST_APP_42=magic
   244      helloWorld=true
   245      TEST_PASSTHROUGH=howdy
   246      HOME=/root
   247      123qwe=bar
   248      org.spring.config=something
   249  
   250      $ docker run --env-file ./env.list busybox env
   251      PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
   252      HOSTNAME=5198e0745561
   253      TEST_FOO=BAR
   254      TEST_APP_DEST_HOST=10.10.0.127
   255      TEST_APP_DEST_PORT=8888
   256      _TEST_BAR=FOO
   257      TEST_APP_42=magic
   258      helloWorld=true
   259      TEST_PASSTHROUGH=
   260      HOME=/root
   261      123qwe=bar
   262      org.spring.config=something
   263  
   264  ### Set metadata on container (-l, --label, --label-file)
   265  
   266  A label is a `key=value` pair that applies metadata to a container. To label a container with two labels:
   267  
   268      $ docker run -l my-label --label com.example.foo=bar ubuntu bash
   269  
   270  The `my-label` key doesn't specify a value so the label defaults to an empty
   271  string(`""`). To add multiple labels, repeat the label flag (`-l` or `--label`).
   272  
   273  The `key=value` must be unique to avoid overwriting the label value. If you
   274  specify labels with identical keys but different values, each subsequent value
   275  overwrites the previous. Docker uses the last `key=value` you supply.
   276  
   277  Use the `--label-file` flag to load multiple labels from a file. Delimit each
   278  label in the file with an EOL mark. The example below loads labels from a
   279  labels file in the current directory:
   280  
   281      $ docker run --label-file ./labels ubuntu bash
   282  
   283  The label-file format is similar to the format for loading environment
   284  variables. (Unlike environment variables, labels are not visible to processes
   285  running inside a container.) The following example illustrates a label-file
   286  format:
   287  
   288      com.example.label1="a label"
   289  
   290      # this is a comment
   291      com.example.label2=another\ label
   292      com.example.label3
   293  
   294  You can load multiple label-files by supplying multiple  `--label-file` flags.
   295  
   296  For additional information on working with labels, see [*Labels - custom
   297  metadata in Docker*](../../userguide/labels-custom-metadata.md) in the Docker User
   298  Guide.
   299  
   300  ### Connect a container to a network (--net)
   301  
   302  When you start a container use the `--net` flag to connect it to a network.
   303  This adds the `busybox` container to the `mynet` network.
   304  
   305  ```bash
   306  $ docker run -itd --net=my-multihost-network busybox
   307  ```
   308  
   309  If you want to add a running container to a network use the `docker network connect` subcommand.
   310  
   311  You can connect multiple containers to the same network. Once connected, the
   312  containers can communicate easily need only another container's IP address
   313  or name. For `overlay` networks or custom plugins that support multi-host
   314  connectivity, containers connected to the same multi-host network but launched
   315  from different Engines can also communicate in this way.
   316  
   317  **Note**: Service discovery is unavailable on the default bridge network.
   318  Containers can communicate via their IP addresses by default. To communicate
   319  by name, they must be linked.
   320  
   321  You can disconnect a container from a network using the `docker network
   322  disconnect` command.
   323  
   324  ### Mount volumes from container (--volumes-from)
   325  
   326      $ docker run --volumes-from 777f7dc92da7 --volumes-from ba8c0c54f0f2:ro -i -t ubuntu pwd
   327  
   328  The `--volumes-from` flag mounts all the defined volumes from the referenced
   329  containers. Containers can be specified by repetitions of the `--volumes-from`
   330  argument. The container ID may be optionally suffixed with `:ro` or `:rw` to
   331  mount the volumes in read-only or read-write mode, respectively. By default,
   332  the volumes are mounted in the same mode (read write or read only) as
   333  the reference container.
   334  
   335  Labeling systems like SELinux require that proper labels are placed on volume
   336  content mounted into a container. Without a label, the security system might
   337  prevent the processes running inside the container from using the content. By
   338  default, Docker does not change the labels set by the OS.
   339  
   340  To change the label in the container context, you can add either of two suffixes
   341  `:z` or `:Z` to the volume mount. These suffixes tell Docker to relabel file
   342  objects on the shared volumes. The `z` option tells Docker that two containers
   343  share the volume content. As a result, Docker labels the content with a shared
   344  content label. Shared volume labels allow all containers to read/write content.
   345  The `Z` option tells Docker to label the content with a private unshared label.
   346  Only the current container can use a private volume.
   347  
   348  ### Attach to STDIN/STDOUT/STDERR (-a)
   349  
   350  The `-a` flag tells `docker run` to bind to the container's `STDIN`, `STDOUT`
   351  or `STDERR`. This makes it possible to manipulate the output and input as
   352  needed.
   353  
   354      $ echo "test" | docker run -i -a stdin ubuntu cat -
   355  
   356  This pipes data into a container and prints the container's ID by attaching
   357  only to the container's `STDIN`.
   358  
   359      $ docker run -a stderr ubuntu echo test
   360  
   361  This isn't going to print anything unless there's an error because we've
   362  only attached to the `STDERR` of the container. The container's logs
   363  still store what's been written to `STDERR` and `STDOUT`.
   364  
   365      $ cat somefile | docker run -i -a stdin mybuilder dobuild
   366  
   367  This is how piping a file into a container could be done for a build.
   368  The container's ID will be printed after the build is done and the build
   369  logs could be retrieved using `docker logs`. This is
   370  useful if you need to pipe a file or something else into a container and
   371  retrieve the container's ID once the container has finished running.
   372  
   373  ### Add host device to container (--device)
   374  
   375      $ docker run --device=/dev/sdc:/dev/xvdc --device=/dev/sdd --device=/dev/zero:/dev/nulo -i -t ubuntu ls -l /dev/{xvdc,sdd,nulo}
   376      brw-rw---- 1 root disk 8, 2 Feb  9 16:05 /dev/xvdc
   377      brw-rw---- 1 root disk 8, 3 Feb  9 16:05 /dev/sdd
   378      crw-rw-rw- 1 root root 1, 5 Feb  9 16:05 /dev/nulo
   379  
   380  It is often necessary to directly expose devices to a container. The `--device`
   381  option enables that. For example, a specific block storage device or loop
   382  device or audio device can be added to an otherwise unprivileged container
   383  (without the `--privileged` flag) and have the application directly access it.
   384  
   385  By default, the container will be able to `read`, `write` and `mknod` these devices.
   386  This can be overridden using a third `:rwm` set of options to each `--device`
   387  flag:
   388  
   389  
   390      $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk  /dev/xvdc
   391  
   392      Command (m for help): q
   393      $ docker run --device=/dev/sda:/dev/xvdc:ro --rm -it ubuntu fdisk  /dev/xvdc
   394      You will not be able to write the partition table.
   395  
   396      Command (m for help): q
   397  
   398      $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk  /dev/xvdc
   399  
   400      Command (m for help): q
   401  
   402      $ docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk  /dev/xvdc
   403      fdisk: unable to open /dev/xvdc: Operation not permitted
   404  
   405  > **Note:**
   406  > `--device` cannot be safely used with ephemeral devices. Block devices
   407  > that may be removed should not be added to untrusted containers with
   408  > `--device`.
   409  
   410  ### Restart policies (--restart)
   411  
   412  Use Docker's `--restart` to specify a container's *restart policy*. A restart
   413  policy controls whether the Docker daemon restarts a container after exit.
   414  Docker supports the following restart policies:
   415  
   416  <table>
   417    <thead>
   418      <tr>
   419        <th>Policy</th>
   420        <th>Result</th>
   421      </tr>
   422    </thead>
   423    <tbody>
   424      <tr>
   425        <td><strong>no</strong></td>
   426        <td>
   427          Do not automatically restart the container when it exits. This is the
   428          default.
   429        </td>
   430      </tr>
   431      <tr>
   432        <td>
   433          <span style="white-space: nowrap">
   434            <strong>on-failure</strong>[:max-retries]
   435          </span>
   436        </td>
   437        <td>
   438          Restart only if the container exits with a non-zero exit status.
   439          Optionally, limit the number of restart retries the Docker
   440          daemon attempts.
   441        </td>
   442      </tr>
   443      <tr>
   444        <td><strong>always</strong></td>
   445        <td>
   446          Always restart the container regardless of the exit status.
   447          When you specify always, the Docker daemon will try to restart
   448          the container indefinitely. The container will also always start
   449          on daemon startup, regardless of the current state of the container.
   450        </td>
   451      </tr>
   452      <tr>
   453        <td><strong>unless-stopped</strong></td>
   454        <td>
   455          Always restart the container regardless of the exit status, but
   456          do not start it on daemon startup if the container has been put
   457          to a stopped state before.
   458        </td>
   459      </tr>
   460    </tbody>
   461  </table>
   462  
   463      $ docker run --restart=always redis
   464  
   465  This will run the `redis` container with a restart policy of **always**
   466  so that if the container exits, Docker will restart it.
   467  
   468  More detailed information on restart policies can be found in the
   469  [Restart Policies (--restart)](../run.md#restart-policies-restart)
   470  section of the Docker run reference page.
   471  
   472  ### Add entries to container hosts file (--add-host)
   473  
   474  You can add other hosts into a container's `/etc/hosts` file by using one or
   475  more `--add-host` flags. This example adds a static address for a host named
   476  `docker`:
   477  
   478      $ docker run --add-host=docker:10.180.0.1 --rm -it debian
   479      $$ ping docker
   480      PING docker (10.180.0.1): 48 data bytes
   481      56 bytes from 10.180.0.1: icmp_seq=0 ttl=254 time=7.600 ms
   482      56 bytes from 10.180.0.1: icmp_seq=1 ttl=254 time=30.705 ms
   483      ^C--- docker ping statistics ---
   484      2 packets transmitted, 2 packets received, 0% packet loss
   485      round-trip min/avg/max/stddev = 7.600/19.152/30.705/11.553 ms
   486  
   487  Sometimes you need to connect to the Docker host from within your
   488  container. To enable this, pass the Docker host's IP address to
   489  the container using the `--add-host` flag. To find the host's address,
   490  use the `ip addr show` command.
   491  
   492  The flags you pass to `ip addr show` depend on whether you are
   493  using IPv4 or IPv6 networking in your containers. Use the following
   494  flags for IPv4 address retrieval for a network device named `eth0`:
   495  
   496      $ HOSTIP=`ip -4 addr show scope global dev eth0 | grep inet | awk '{print \$2}' | cut -d / -f 1`
   497      $ docker run  --add-host=docker:${HOSTIP} --rm -it debian
   498  
   499  For IPv6 use the `-6` flag instead of the `-4` flag. For other network
   500  devices, replace `eth0` with the correct device name (for example `docker0`
   501  for the bridge device).
   502  
   503  ### Set ulimits in container (--ulimit)
   504  
   505  Since setting `ulimit` settings in a container requires extra privileges not
   506  available in the default container, you can set these using the `--ulimit` flag.
   507  `--ulimit` is specified with a soft and hard limit as such:
   508  `<type>=<soft limit>[:<hard limit>]`, for example:
   509  
   510      $ docker run --ulimit nofile=1024:1024 --rm debian ulimit -n
   511      1024
   512  
   513  > **Note:**
   514  > If you do not provide a `hard limit`, the `soft limit` will be used
   515  > for both values. If no `ulimits` are set, they will be inherited from
   516  > the default `ulimits` set on the daemon.  `as` option is disabled now.
   517  > In other words, the following script is not supported:
   518  > `$ docker run -it --ulimit as=1024 fedora /bin/bash`
   519  
   520  The values are sent to the appropriate `syscall` as they are set.
   521  Docker doesn't perform any byte conversion. Take this into account when setting the values.
   522  
   523  #### For `nproc` usage
   524  
   525  Be careful setting `nproc` with the `ulimit` flag as `nproc` is designed by Linux to set the
   526  maximum number of processes available to a user, not to a container.  For example, start four
   527  containers with `daemon` user:
   528  
   529      docker run -d -u daemon --ulimit nproc=3 busybox top
   530      docker run -d -u daemon --ulimit nproc=3 busybox top
   531      docker run -d -u daemon --ulimit nproc=3 busybox top
   532      docker run -d -u daemon --ulimit nproc=3 busybox top
   533  
   534  The 4th container fails and reports "[8] System error: resource temporarily unavailable" error.
   535  This fails because the caller set `nproc=3` resulting in the first three containers using up
   536  the three processes quota set for the `daemon` user.
   537  
   538  ### Stop container with signal (--stop-signal)
   539  
   540  The `--stop-signal` flag sets the system call signal that will be sent to the container to exit.
   541  This signal can be a valid unsigned number that matches a position in the kernel's syscall table, for instance 9,
   542  or a signal name in the format SIGNAME, for instance SIGKILL.