github.1git.de/docker/cli@v26.1.3+incompatible/docs/reference/run.md (about)

     1  ---
     2  description: "Running and configuring containers with the Docker CLI"
     3  keywords: "docker, run, cli"
     4  aliases:
     5  - /reference/run/
     6  title: Running containers
     7  ---
     8  
     9  Docker runs processes in isolated containers. A container is a process
    10  which runs on a host. The host may be local or remote. When you
    11  execute `docker run`, the container process that runs is isolated in
    12  that it has its own file system, its own networking, and its own
    13  isolated process tree separate from the host.
    14  
    15  This page details how to use the `docker run` command to run containers.
    16  
    17  ## General form
    18  
    19  A `docker run` command takes the following form:
    20  
    21  ```console
    22  $ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]
    23  ```
    24  
    25  The `docker run` command must specify an [image reference](#image-references)
    26  to create the container from.
    27  
    28  ### Image references
    29  
    30  The image reference is the name and version of the image. You can use the image
    31  reference to create or run a container based on an image.
    32  
    33  - `docker run IMAGE[:TAG][@DIGEST]`
    34  - `docker create IMAGE[:TAG][@DIGEST]`
    35  
    36  An image tag is the image version, which defaults to `latest` when omitted. Use
    37  the tag to run a container from specific version of an image. For example, to
    38  run version `23.10` of the `ubuntu` image: `docker run ubuntu:23.10`.
    39  
    40  #### Image digests
    41  
    42  Images using the v2 or later image format have a content-addressable identifier
    43  called a digest. As long as the input used to generate the image is unchanged,
    44  the digest value is predictable.
    45  
    46  The following example runs a container from the `alpine` image with the
    47  `sha256:9cacb71397b640eca97488cf08582ae4e4068513101088e9f96c9814bfda95e0` digest:
    48  
    49  ```console
    50  $ docker run alpine@sha256:9cacb71397b640eca97488cf08582ae4e4068513101088e9f96c9814bfda95e0 date
    51  ```
    52  
    53  ### Options
    54  
    55  `[OPTIONS]` let you configure options for the container. For example, you can
    56  give the container a name (`--name`), or run it as a background process (`-d`).
    57  You can also set options to control things like resource constraints and
    58  networking.
    59  
    60  ### Commands and arguments
    61  
    62  You can use the `[COMMAND]` and `[ARG...]` positional arguments to specify
    63  commands and arguments for the container to run when it starts up. For example,
    64  you can specify `sh` as the `[COMMAND]`, combined with the `-i` and `-t` flags,
    65  to start an interactive shell in the container (if the image you select has an
    66  `sh` executable on `PATH`).
    67  
    68  ```console
    69  $ docker run -it IMAGE sh
    70  ```
    71  
    72  > **Note**
    73  >
    74  > Depending on your Docker system configuration, you may be
    75  > required to preface the `docker run` command with `sudo`. To avoid
    76  > having to use `sudo` with the `docker` command, your system
    77  > administrator can create a Unix group called `docker` and add users to
    78  > it. For more information about this configuration, refer to the Docker
    79  > installation documentation for your operating system.
    80  
    81  ## Foreground and background
    82  
    83  When you start a container, the container runs in the foreground by default.
    84  If you want to run the container in the background instead, you can use the
    85  `--detach` (or `-d`) flag. This starts the container without occupying your
    86  terminal window.
    87  
    88  ```console
    89  $ docker run -d <IMAGE>
    90  ```
    91  
    92  While the container runs in the background, you can interact with the container
    93  using other CLI commands. For example, `docker logs` lets you view the logs for
    94  the container, and `docker attach` brings it to the foreground.
    95  
    96  ```console
    97  $ docker run -d nginx
    98  0246aa4d1448a401cabd2ce8f242192b6e7af721527e48a810463366c7ff54f1
    99  $ docker ps
   100  CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS        PORTS     NAMES
   101  0246aa4d1448   nginx     "/docker-entrypoint.…"   2 seconds ago   Up 1 second   80/tcp    pedantic_liskov
   102  $ docker logs -n 5 0246aa4d1448
   103  2023/11/06 15:58:23 [notice] 1#1: start worker process 33
   104  2023/11/06 15:58:23 [notice] 1#1: start worker process 34
   105  2023/11/06 15:58:23 [notice] 1#1: start worker process 35
   106  2023/11/06 15:58:23 [notice] 1#1: start worker process 36
   107  2023/11/06 15:58:23 [notice] 1#1: start worker process 37
   108  $ docker attach 0246aa4d1448
   109  ^C
   110  2023/11/06 15:58:40 [notice] 1#1: signal 2 (SIGINT) received, exiting
   111  ...
   112  ```
   113  
   114  For more information about `docker run` flags related to foreground and
   115  background modes, see:
   116  
   117  - [`docker run --detach`](https://docs.docker.com/reference/cli/docker/container/run/#detach): run container in background
   118  - [`docker run --attach`](https://docs.docker.com/reference/cli/docker/container/run/#attach): attach to `stdin`, `stdout`, and `stderr`
   119  - [`docker run --tty`](https://docs.docker.com/reference/cli/docker/container/run/#tty): allocate a pseudo-tty
   120  - [`docker run --interactive`](https://docs.docker.com/reference/cli/docker/container/run/#interactive): keep `stdin` open even if not attached
   121  
   122  For more information about re-attaching to a background container, see
   123  [`docker attach`](https://docs.docker.com/reference/cli/docker/container/attach/).
   124  
   125  ## Container identification
   126  
   127  You can identify a container in three ways:
   128  
   129  | Identifier type       | Example value                                                      |
   130  |:----------------------|:-------------------------------------------------------------------|
   131  | UUID long identifier  | `f78375b1c487e03c9438c729345e54db9d20cfa2ac1fc3494b6eb60872e74778` |
   132  | UUID short identifier | `f78375b1c487`                                                     |
   133  | Name                  | `evil_ptolemy`                                                     |
   134  
   135  The UUID identifier is a random ID assigned to the container by the daemon.
   136  
   137  The daemon generates a random string name for containers automatically. You can
   138  also defined a custom name using [the `--name` flag](https://docs.docker.com/reference/cli/docker/container/run/#name).
   139  Defining a `name` can be a handy way to add meaning to a container. If you
   140  specify a `name`, you can use it when referring to the container in a
   141  user-defined network. This works for both background and foreground Docker
   142  containers.
   143  
   144  A container identifier is not the same thing as an image reference. The image
   145  reference specifies which image to use when you run a container. You can't run
   146  `docker exec nginx:alpine sh` to open a shell in a container based on the
   147  `nginx:alpine` image, because `docker exec` expects a container identifier
   148  (name or ID), not an image.
   149  
   150  While the image used by a container is not an identifier for the container, you
   151  find out the IDs of containers using an image by using the `--filter` flag. For
   152  example, the following `docker ps` command gets the IDs of all running
   153  containers based on the `nginx:alpine` image:
   154  
   155  ```console
   156  $ docker ps -q --filter ancestor=nginx:alpine
   157  ```
   158  
   159  For more information about using filters, see
   160  [Filtering](https://docs.docker.com/config/filter/).
   161  
   162  ## Container networking
   163  
   164  Containers have networking enabled by default, and they can make outgoing
   165  connections. If you're running multiple containers that need to communicate
   166  with each other, you can create a custom network and attach the containers to
   167  the network.
   168  
   169  When multiple containers are attached to the same custom network, they can
   170  communicate with each other using the container names as a DNS hostname. The
   171  following example creates a custom network named `my-net`, and runs two
   172  containers that attach to the network.
   173  
   174  ```console
   175  $ docker network create my-net
   176  $ docker run -d --name web --network my-net nginx:alpine
   177  $ docker run --rm -it --network my-net busybox
   178  / # ping web
   179  PING web (172.18.0.2): 56 data bytes
   180  64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.326 ms
   181  64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.257 ms
   182  64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.281 ms
   183  ^C
   184  --- web ping statistics ---
   185  3 packets transmitted, 3 packets received, 0% packet loss
   186  round-trip min/avg/max = 0.257/0.288/0.326 ms
   187  ```
   188  
   189  For more information about container networking, see [Networking
   190  overview](https://docs.docker.com/network/)
   191  
   192  ## Filesystem mounts
   193  
   194  By default, the data in a container is stored in an ephemeral, writable
   195  container layer. Removing the container also removes its data. If you want to
   196  use persistent data with containers, you can use filesystem mounts to store the
   197  data persistently on the host system. Filesystem mounts can also let you share
   198  data between containers and the host.
   199  
   200  Docker supports two main categories of mounts:
   201  
   202  - Volume mounts
   203  - Bind mounts
   204  
   205  Volume mounts are great for persistently storing data for containers, and for
   206  sharing data between containers. Bind mounts, on the other hand, are for
   207  sharing data between a container and the host.
   208  
   209  You can add a filesystem mount to a container using the `--mount` flag for the
   210  `docker run` command.
   211  
   212  The following sections show basic examples of how to create volumes and bind
   213  mounts. For more in-depth examples and descriptions, refer to the section of
   214  the [storage section](https://docs.docker.com/storage/) in the documentation.
   215  
   216  ### Volume mounts
   217  
   218  To create a volume mount:
   219  
   220  ```console
   221  $ docker run --mount source=<VOLUME_NAME>,target=[PATH] [IMAGE] [COMMAND...]
   222  ```
   223  
   224  The `--mount` flag takes two parameters in this case: `source` and `target`.
   225  The value for the `source` parameter is the name of the volume. The value of
   226  `target` is the mount location of the volume inside the container. Once you've
   227  created the volume, any data you write to the volume is persisted, even if you
   228  stop or remove the container:
   229  
   230  ```console
   231  $ docker run --rm --mount source=my_volume,target=/foo busybox \
   232    echo "hello, volume!" > /foo/hello.txt
   233  $ docker run --mount source=my_volume,target=/bar busybox
   234    cat /bar/hello.txt
   235  hello, volume!
   236  ```
   237  
   238  The `target` must always be an absolute path, such as `/src/docs`. An absolute
   239  path starts with a `/` (forward slash). Volume names must start with an
   240  alphanumeric character, followed by `a-z0-9`, `_` (underscore), `.` (period) or
   241  `-` (hyphen).
   242  
   243  ### Bind mounts
   244  
   245  To create a bind mount:
   246  
   247  ```console
   248  $ docker run -it --mount type=bind,source=[PATH],target=[PATH] busybox
   249  ```
   250  
   251  In this case, the `--mount` flag takes three parameters. A type (`bind`), and
   252  two paths. The `source` path is a the location on the host that you want to
   253  bind mount into the container. The `target` path is the mount destination
   254  inside the container.
   255  
   256  Bind mounts are read-write by default, meaning that you can both read and write
   257  files to and from the mounted location from the container. Changes that you
   258  make, such as adding or editing files, are reflected on the host filesystem:
   259  
   260  ```console
   261  $ docker run -it --mount type=bind,source=.,target=/foo busybox
   262  / # echo "hello from container" > /foo/hello.txt
   263  / # exit
   264  $ cat hello.txt
   265  hello from container
   266  ```
   267  
   268  ## Exit status
   269  
   270  The exit code from `docker run` gives information about why the container
   271  failed to run or why it exited. The following sections describe the meanings of
   272  different container exit codes values.
   273  
   274  ### 125
   275  
   276  Exit code `125` indicates that the error is with Docker daemon itself.
   277  
   278  ```console
   279  $ docker run --foo busybox; echo $?
   280  
   281  flag provided but not defined: --foo
   282  See 'docker run --help'.
   283  125
   284  ```
   285  
   286  ### 126
   287  
   288  Exit code `126` indicates that the specified contained command can't be invoked.
   289  The container command in the following example is: `/etc; echo $?`.
   290  
   291  ```console
   292  $ docker run busybox /etc; echo $?
   293  
   294  docker: Error response from daemon: Container command '/etc' could not be invoked.
   295  126
   296  ```
   297  
   298  ### 127
   299  
   300  Exit code `127` indicates that the contained command can't be found.
   301  
   302  ```console
   303  $ docker run busybox foo; echo $?
   304  
   305  docker: Error response from daemon: Container command 'foo' not found or does not exist.
   306  127
   307  ```
   308  
   309  ### Other exit codes
   310  
   311  Any exit code other than `125`, `126`, and `127` represent the exit code of the
   312  provided container command.
   313  
   314  ```console
   315  $ docker run busybox /bin/sh -c 'exit 3'
   316  $ echo $?
   317  3
   318  ```
   319  
   320  ## Runtime constraints on resources
   321  
   322  The operator can also adjust the performance parameters of the
   323  container:
   324  
   325  | Option                     | Description                                                                                                                                                                                                                                                                              |
   326  |:---------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
   327  | `-m`, `--memory=""`        | Memory limit (format: `<number>[<unit>]`). Number is a positive integer. Unit can be one of `b`, `k`, `m`, or `g`. Minimum is 6M.                                                                                                                                                        |
   328  | `--memory-swap=""`         | Total memory limit (memory + swap, format: `<number>[<unit>]`). Number is a positive integer. Unit can be one of `b`, `k`, `m`, or `g`.                                                                                                                                                  |
   329  | `--memory-reservation=""`  | Memory soft limit (format: `<number>[<unit>]`). Number is a positive integer. Unit can be one of `b`, `k`, `m`, or `g`.                                                                                                                                                                  |
   330  | `--kernel-memory=""`       | Kernel memory limit (format: `<number>[<unit>]`). Number is a positive integer. Unit can be one of `b`, `k`, `m`, or `g`. Minimum is 4M.                                                                                                                                                 |
   331  | `-c`, `--cpu-shares=0`     | CPU shares (relative weight)                                                                                                                                                                                                                                                             |
   332  | `--cpus=0.000`             | Number of CPUs. Number is a fractional number. 0.000 means no limit.                                                                                                                                                                                                                     |
   333  | `--cpu-period=0`           | Limit the CPU CFS (Completely Fair Scheduler) period                                                                                                                                                                                                                                     |
   334  | `--cpuset-cpus=""`         | CPUs in which to allow execution (0-3, 0,1)                                                                                                                                                                                                                                              |
   335  | `--cpuset-mems=""`         | Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.                                                                                                                                                                                              |
   336  | `--cpu-quota=0`            | Limit the CPU CFS (Completely Fair Scheduler) quota                                                                                                                                                                                                                                      |
   337  | `--cpu-rt-period=0`        | Limit the CPU real-time period. In microseconds. Requires parent cgroups be set and cannot be higher than parent. Also check rtprio ulimits.                                                                                                                                             |
   338  | `--cpu-rt-runtime=0`       | Limit the CPU real-time runtime. In microseconds. Requires parent cgroups be set and cannot be higher than parent. Also check rtprio ulimits.                                                                                                                                            |
   339  | `--blkio-weight=0`         | Block IO weight (relative weight) accepts a weight value between 10 and 1000.                                                                                                                                                                                                            |
   340  | `--blkio-weight-device=""` | Block IO weight (relative device weight, format: `DEVICE_NAME:WEIGHT`)                                                                                                                                                                                                                   |
   341  | `--device-read-bps=""`     | Limit read rate from a device (format: `<device-path>:<number>[<unit>]`). Number is a positive integer. Unit can be one of `kb`, `mb`, or `gb`.                                                                                                                                          |
   342  | `--device-write-bps=""`    | Limit write rate to a device (format: `<device-path>:<number>[<unit>]`). Number is a positive integer. Unit can be one of `kb`, `mb`, or `gb`.                                                                                                                                           |
   343  | `--device-read-iops="" `   | Limit read rate (IO per second) from a device (format: `<device-path>:<number>`). Number is a positive integer.                                                                                                                                                                          |
   344  | `--device-write-iops="" `  | Limit write rate (IO per second) to a device (format: `<device-path>:<number>`). Number is a positive integer.                                                                                                                                                                           |
   345  | `--oom-kill-disable=false` | Whether to disable OOM Killer for the container or not.                                                                                                                                                                                                                                  |
   346  | `--oom-score-adj=0`        | Tune container's OOM preferences (-1000 to 1000)                                                                                                                                                                                                                                         |
   347  | `--memory-swappiness=""`   | Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100.                                                                                                                                                                                                     |
   348  | `--shm-size=""`            | Size of `/dev/shm`. The format is `<number><unit>`. `number` must be greater than `0`. Unit is optional and can be `b` (bytes), `k` (kilobytes), `m` (megabytes), or `g` (gigabytes). If you omit the unit, the system uses bytes. If you omit the size entirely, the system uses `64m`. |
   349  
   350  ### User memory constraints
   351  
   352  We have four ways to set user memory usage:
   353  
   354  <table>
   355    <thead>
   356      <tr>
   357        <th>Option</th>
   358        <th>Result</th>
   359      </tr>
   360    </thead>
   361    <tbody>
   362      <tr>
   363        <td class="no-wrap">
   364            <strong>memory=inf, memory-swap=inf</strong> (default)
   365        </td>
   366        <td>
   367          There is no memory limit for the container. The container can use
   368          as much memory as needed.
   369        </td>
   370      </tr>
   371      <tr>
   372        <td class="no-wrap"><strong>memory=L&lt;inf, memory-swap=inf</strong></td>
   373        <td>
   374          (specify memory and set memory-swap as <code>-1</code>) The container is
   375          not allowed to use more than L bytes of memory, but can use as much swap
   376          as is needed (if the host supports swap memory).
   377        </td>
   378      </tr>
   379      <tr>
   380        <td class="no-wrap"><strong>memory=L&lt;inf, memory-swap=2*L</strong></td>
   381        <td>
   382          (specify memory without memory-swap) The container is not allowed to
   383          use more than L bytes of memory, swap <i>plus</i> memory usage is double
   384          of that.
   385        </td>
   386      </tr>
   387      <tr>
   388        <td class="no-wrap">
   389            <strong>memory=L&lt;inf, memory-swap=S&lt;inf, L&lt;=S</strong>
   390        </td>
   391        <td>
   392          (specify both memory and memory-swap) The container is not allowed to
   393          use more than L bytes of memory, swap <i>plus</i> memory usage is limited
   394          by S.
   395        </td>
   396      </tr>
   397    </tbody>
   398  </table>
   399  
   400  Examples:
   401  
   402  ```console
   403  $ docker run -it ubuntu:22.04 /bin/bash
   404  ```
   405  
   406  We set nothing about memory, this means the processes in the container can use
   407  as much memory and swap memory as they need.
   408  
   409  ```console
   410  $ docker run -it -m 300M --memory-swap -1 ubuntu:22.04 /bin/bash
   411  ```
   412  
   413  We set memory limit and disabled swap memory limit, this means the processes in
   414  the container can use 300M memory and as much swap memory as they need (if the
   415  host supports swap memory).
   416  
   417  ```console
   418  $ docker run -it -m 300M ubuntu:22.04 /bin/bash
   419  ```
   420  
   421  We set memory limit only, this means the processes in the container can use
   422  300M memory and 300M swap memory, by default, the total virtual memory size
   423  (--memory-swap) will be set as double of memory, in this case, memory + swap
   424  would be 2*300M, so processes can use 300M swap memory as well.
   425  
   426  ```console
   427  $ docker run -it -m 300M --memory-swap 1G ubuntu:22.04 /bin/bash
   428  ```
   429  
   430  We set both memory and swap memory, so the processes in the container can use
   431  300M memory and 700M swap memory.
   432  
   433  Memory reservation is a kind of memory soft limit that allows for greater
   434  sharing of memory. Under normal circumstances, containers can use as much of
   435  the memory as needed and are constrained only by the hard limits set with the
   436  `-m`/`--memory` option. When memory reservation is set, Docker detects memory
   437  contention or low memory and forces containers to restrict their consumption to
   438  a reservation limit.
   439  
   440  Always set the memory reservation value below the hard limit, otherwise the hard
   441  limit takes precedence. A reservation of 0 is the same as setting no
   442  reservation. By default (without reservation set), memory reservation is the
   443  same as the hard memory limit.
   444  
   445  Memory reservation is a soft-limit feature and does not guarantee the limit
   446  won't be exceeded. Instead, the feature attempts to ensure that, when memory is
   447  heavily contended for, memory is allocated based on the reservation hints/setup.
   448  
   449  The following example limits the memory (`-m`) to 500M and sets the memory
   450  reservation to 200M.
   451  
   452  ```console
   453  $ docker run -it -m 500M --memory-reservation 200M ubuntu:22.04 /bin/bash
   454  ```
   455  
   456  Under this configuration, when the container consumes memory more than 200M and
   457  less than 500M, the next system memory reclaim attempts to shrink container
   458  memory below 200M.
   459  
   460  The following example set memory reservation to 1G without a hard memory limit.
   461  
   462  ```console
   463  $ docker run -it --memory-reservation 1G ubuntu:22.04 /bin/bash
   464  ```
   465  
   466  The container can use as much memory as it needs. The memory reservation setting
   467  ensures the container doesn't consume too much memory for long time, because
   468  every memory reclaim shrinks the container's consumption to the reservation.
   469  
   470  By default, kernel kills processes in a container if an out-of-memory (OOM)
   471  error occurs. To change this behaviour, use the `--oom-kill-disable` option.
   472  Only disable the OOM killer on containers where you have also set the
   473  `-m/--memory` option. If the `-m` flag is not set, this can result in the host
   474  running out of memory and require killing the host's system processes to free
   475  memory.
   476  
   477  The following example limits the memory to 100M and disables the OOM killer for
   478  this container:
   479  
   480  ```console
   481  $ docker run -it -m 100M --oom-kill-disable ubuntu:22.04 /bin/bash
   482  ```
   483  
   484  The following example, illustrates a dangerous way to use the flag:
   485  
   486  ```console
   487  $ docker run -it --oom-kill-disable ubuntu:22.04 /bin/bash
   488  ```
   489  
   490  The container has unlimited memory which can cause the host to run out memory
   491  and require killing system processes to free memory. The `--oom-score-adj`
   492  parameter can be changed to select the priority of which containers will
   493  be killed when the system is out of memory, with negative scores making them
   494  less likely to be killed, and positive scores more likely.
   495  
   496  ### Kernel memory constraints
   497  
   498  Kernel memory is fundamentally different than user memory as kernel memory can't
   499  be swapped out. The inability to swap makes it possible for the container to
   500  block system services by consuming too much kernel memory. Kernel memory includes:
   501  
   502   - stack pages
   503   - slab pages
   504   - sockets memory pressure
   505   - tcp memory pressure
   506  
   507  You can setup kernel memory limit to constrain these kinds of memory. For example,
   508  every process consumes some stack pages. By limiting kernel memory, you can
   509  prevent new processes from being created when the kernel memory usage is too high.
   510  
   511  Kernel memory is never completely independent of user memory. Instead, you limit
   512  kernel memory in the context of the user memory limit. Assume "U" is the user memory
   513  limit and "K" the kernel limit. There are three possible ways to set limits:
   514  
   515  <table>
   516    <thead>
   517      <tr>
   518        <th>Option</th>
   519        <th>Result</th>
   520      </tr>
   521    </thead>
   522    <tbody>
   523      <tr>
   524        <td class="no-wrap"><strong>U != 0, K = inf</strong> (default)</td>
   525        <td>
   526          This is the standard memory limitation mechanism already present before using
   527          kernel memory. Kernel memory is completely ignored.
   528        </td>
   529      </tr>
   530      <tr>
   531        <td class="no-wrap"><strong>U != 0, K &lt; U</strong></td>
   532        <td>
   533          Kernel memory is a subset of the user memory. This setup is useful in
   534          deployments where the total amount of memory per-cgroup is overcommitted.
   535          Overcommitting kernel memory limits is definitely not recommended, since the
   536          box can still run out of non-reclaimable memory.
   537          In this case, you can configure K so that the sum of all groups is
   538          never greater than the total memory. Then, freely set U at the expense of
   539          the system's service quality.
   540        </td>
   541      </tr>
   542      <tr>
   543        <td class="no-wrap"><strong>U != 0, K &gt; U</strong></td>
   544        <td>
   545          Since kernel memory charges are also fed to the user counter and reclamation
   546          is triggered for the container for both kinds of memory. This configuration
   547          gives the admin a unified view of memory. It is also useful for people
   548          who just want to track kernel memory usage.
   549        </td>
   550      </tr>
   551    </tbody>
   552  </table>
   553  
   554  Examples:
   555  
   556  ```console
   557  $ docker run -it -m 500M --kernel-memory 50M ubuntu:22.04 /bin/bash
   558  ```
   559  
   560  We set memory and kernel memory, so the processes in the container can use
   561  500M memory in total, in this 500M memory, it can be 50M kernel memory tops.
   562  
   563  ```console
   564  $ docker run -it --kernel-memory 50M ubuntu:22.04 /bin/bash
   565  ```
   566  
   567  We set kernel memory without **-m**, so the processes in the container can
   568  use as much memory as they want, but they can only use 50M kernel memory.
   569  
   570  ### Swappiness constraint
   571  
   572  By default, a container's kernel can swap out a percentage of anonymous pages.
   573  To set this percentage for a container, specify a `--memory-swappiness` value
   574  between 0 and 100. A value of 0 turns off anonymous page swapping. A value of
   575  100 sets all anonymous pages as swappable. By default, if you are not using
   576  `--memory-swappiness`, memory swappiness value will be inherited from the parent.
   577  
   578  For example, you can set:
   579  
   580  ```console
   581  $ docker run -it --memory-swappiness=0 ubuntu:22.04 /bin/bash
   582  ```
   583  
   584  Setting the `--memory-swappiness` option is helpful when you want to retain the
   585  container's working set and to avoid swapping performance penalties.
   586  
   587  ### CPU share constraint
   588  
   589  By default, all containers get the same proportion of CPU cycles. This proportion
   590  can be modified by changing the container's CPU share weighting relative
   591  to the weighting of all other running containers.
   592  
   593  To modify the proportion from the default of 1024, use the `-c` or `--cpu-shares`
   594  flag to set the weighting to 2 or higher. If 0 is set, the system will ignore the
   595  value and use the default of 1024.
   596  
   597  The proportion will only apply when CPU-intensive processes are running.
   598  When tasks in one container are idle, other containers can use the
   599  left-over CPU time. The actual amount of CPU time will vary depending on
   600  the number of containers running on the system.
   601  
   602  For example, consider three containers, one has a cpu-share of 1024 and
   603  two others have a cpu-share setting of 512. When processes in all three
   604  containers attempt to use 100% of CPU, the first container would receive
   605  50% of the total CPU time. If you add a fourth container with a cpu-share
   606  of 1024, the first container only gets 33% of the CPU. The remaining containers
   607  receive 16.5%, 16.5% and 33% of the CPU.
   608  
   609  On a multi-core system, the shares of CPU time are distributed over all CPU
   610  cores. Even if a container is limited to less than 100% of CPU time, it can
   611  use 100% of each individual CPU core.
   612  
   613  For example, consider a system with more than three cores. If you start one
   614  container `{C0}` with `-c=512` running one process, and another container
   615  `{C1}` with `-c=1024` running two processes, this can result in the following
   616  division of CPU shares:
   617  
   618      PID    container	CPU	CPU share
   619      100    {C0}		0	100% of CPU0
   620      101    {C1}		1	100% of CPU1
   621      102    {C1}		2	100% of CPU2
   622  
   623  ### CPU period constraint
   624  
   625  The default CPU CFS (Completely Fair Scheduler) period is 100ms. We can use
   626  `--cpu-period` to set the period of CPUs to limit the container's CPU usage.
   627  And usually `--cpu-period` should work with `--cpu-quota`.
   628  
   629  Examples:
   630  
   631  ```console
   632  $ docker run -it --cpu-period=50000 --cpu-quota=25000 ubuntu:22.04 /bin/bash
   633  ```
   634  
   635  If there is 1 CPU, this means the container can get 50% CPU worth of run-time every 50ms.
   636  
   637  In addition to use `--cpu-period` and `--cpu-quota` for setting CPU period constraints,
   638  it is possible to specify `--cpus` with a float number to achieve the same purpose.
   639  For example, if there is 1 CPU, then `--cpus=0.5` will achieve the same result as
   640  setting `--cpu-period=50000` and `--cpu-quota=25000` (50% CPU).
   641  
   642  The default value for `--cpus` is `0.000`, which means there is no limit.
   643  
   644  For more information, see the [CFS documentation on bandwidth limiting](https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt).
   645  
   646  ### Cpuset constraint
   647  
   648  We can set cpus in which to allow execution for containers.
   649  
   650  Examples:
   651  
   652  ```console
   653  $ docker run -it --cpuset-cpus="1,3" ubuntu:22.04 /bin/bash
   654  ```
   655  
   656  This means processes in container can be executed on cpu 1 and cpu 3.
   657  
   658  ```console
   659  $ docker run -it --cpuset-cpus="0-2" ubuntu:22.04 /bin/bash
   660  ```
   661  
   662  This means processes in container can be executed on cpu 0, cpu 1 and cpu 2.
   663  
   664  We can set mems in which to allow execution for containers. Only effective
   665  on NUMA systems.
   666  
   667  Examples:
   668  
   669  ```console
   670  $ docker run -it --cpuset-mems="1,3" ubuntu:22.04 /bin/bash
   671  ```
   672  
   673  This example restricts the processes in the container to only use memory from
   674  memory nodes 1 and 3.
   675  
   676  ```console
   677  $ docker run -it --cpuset-mems="0-2" ubuntu:22.04 /bin/bash
   678  ```
   679  
   680  This example restricts the processes in the container to only use memory from
   681  memory nodes 0, 1 and 2.
   682  
   683  ### CPU quota constraint
   684  
   685  The `--cpu-quota` flag limits the container's CPU usage. The default 0 value
   686  allows the container to take 100% of a CPU resource (1 CPU). The CFS (Completely Fair
   687  Scheduler) handles resource allocation for executing processes and is default
   688  Linux Scheduler used by the kernel. Set this value to 50000 to limit the container
   689  to 50% of a CPU resource. For multiple CPUs, adjust the `--cpu-quota` as necessary.
   690  For more information, see the [CFS documentation on bandwidth limiting](https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt).
   691  
   692  ### Block IO bandwidth (Blkio) constraint
   693  
   694  By default, all containers get the same proportion of block IO bandwidth
   695  (blkio). This proportion is 500. To modify this proportion, change the
   696  container's blkio weight relative to the weighting of all other running
   697  containers using the `--blkio-weight` flag.
   698  
   699  > **Note:**
   700  >
   701  > The blkio weight setting is only available for direct IO. Buffered IO is not
   702  > currently supported.
   703  
   704  The `--blkio-weight` flag can set the weighting to a value between 10 to 1000.
   705  For example, the commands below create two containers with different blkio
   706  weight:
   707  
   708  ```console
   709  $ docker run -it --name c1 --blkio-weight 300 ubuntu:22.04 /bin/bash
   710  $ docker run -it --name c2 --blkio-weight 600 ubuntu:22.04 /bin/bash
   711  ```
   712  
   713  If you do block IO in the two containers at the same time, by, for example:
   714  
   715  ```console
   716  $ time dd if=/mnt/zerofile of=test.out bs=1M count=1024 oflag=direct
   717  ```
   718  
   719  You'll find that the proportion of time is the same as the proportion of blkio
   720  weights of the two containers.
   721  
   722  The `--blkio-weight-device="DEVICE_NAME:WEIGHT"` flag sets a specific device weight.
   723  The `DEVICE_NAME:WEIGHT` is a string containing a colon-separated device name and weight.
   724  For example, to set `/dev/sda` device weight to `200`:
   725  
   726  ```console
   727  $ docker run -it \
   728      --blkio-weight-device "/dev/sda:200" \
   729      ubuntu
   730  ```
   731  
   732  If you specify both the `--blkio-weight` and `--blkio-weight-device`, Docker
   733  uses the `--blkio-weight` as the default weight and uses `--blkio-weight-device`
   734  to override this default with a new value on a specific device.
   735  The following example uses a default weight of `300` and overrides this default
   736  on `/dev/sda` setting that weight to `200`:
   737  
   738  ```console
   739  $ docker run -it \
   740      --blkio-weight 300 \
   741      --blkio-weight-device "/dev/sda:200" \
   742      ubuntu
   743  ```
   744  
   745  The `--device-read-bps` flag limits the read rate (bytes per second) from a device.
   746  For example, this command creates a container and limits the read rate to `1mb`
   747  per second from `/dev/sda`:
   748  
   749  ```console
   750  $ docker run -it --device-read-bps /dev/sda:1mb ubuntu
   751  ```
   752  
   753  The `--device-write-bps` flag limits the write rate (bytes per second) to a device.
   754  For example, this command creates a container and limits the write rate to `1mb`
   755  per second for `/dev/sda`:
   756  
   757  ```console
   758  $ docker run -it --device-write-bps /dev/sda:1mb ubuntu
   759  ```
   760  
   761  Both flags take limits in the `<device-path>:<limit>[unit]` format. Both read
   762  and write rates must be a positive integer. You can specify the rate in `kb`
   763  (kilobytes), `mb` (megabytes), or `gb` (gigabytes).
   764  
   765  The `--device-read-iops` flag limits read rate (IO per second) from a device.
   766  For example, this command creates a container and limits the read rate to
   767  `1000` IO per second from `/dev/sda`:
   768  
   769  ```console
   770  $ docker run -it --device-read-iops /dev/sda:1000 ubuntu
   771  ```
   772  
   773  The `--device-write-iops` flag limits write rate (IO per second) to a device.
   774  For example, this command creates a container and limits the write rate to
   775  `1000` IO per second to `/dev/sda`:
   776  
   777  ```console
   778  $ docker run -it --device-write-iops /dev/sda:1000 ubuntu
   779  ```
   780  
   781  Both flags take limits in the `<device-path>:<limit>` format. Both read and
   782  write rates must be a positive integer.
   783  
   784  ## Additional groups
   785  
   786  ```console
   787  --group-add: Add additional groups to run as
   788  ```
   789  
   790  By default, the docker container process runs with the supplementary groups looked
   791  up for the specified user. If one wants to add more to that list of groups, then
   792  one can use this flag:
   793  
   794  ```console
   795  $ docker run --rm --group-add audio --group-add nogroup --group-add 777 busybox id
   796  
   797  uid=0(root) gid=0(root) groups=10(wheel),29(audio),99(nogroup),777
   798  ```
   799  
   800  ## Runtime privilege and Linux capabilities
   801  
   802  | Option         | Description                                                                   |
   803  |:---------------|:------------------------------------------------------------------------------|
   804  | `--cap-add`    | Add Linux capabilities                                                        |
   805  | `--cap-drop`   | Drop Linux capabilities                                                       |
   806  | `--privileged` | Give extended privileges to this container                                    |
   807  | `--device=[]`  | Allows you to run devices inside the container without the `--privileged` flag. |
   808  
   809  By default, Docker containers are "unprivileged" and cannot, for
   810  example, run a Docker daemon inside a Docker container. This is because
   811  by default a container is not allowed to access any devices, but a
   812  "privileged" container is given access to all devices (see
   813  the documentation on [cgroups devices](https://www.kernel.org/doc/Documentation/cgroup-v1/devices.txt)).
   814  
   815  The `--privileged` flag gives all capabilities to the container. When the operator
   816  executes `docker run --privileged`, Docker enables access to all devices on
   817  the host, and reconfigures AppArmor or SELinux to allow the container
   818  nearly all the same access to the host as processes running outside
   819  containers on the host. Use this flag with caution.
   820  For more information about the `--privileged` flag, see the
   821  [`docker run` reference](https://docs.docker.com/reference/cli/docker/container/run/#privileged).
   822  
   823  If you want to limit access to a specific device or devices you can use
   824  the `--device` flag. It allows you to specify one or more devices that
   825  will be accessible within the container.
   826  
   827  ```console
   828  $ docker run --device=/dev/snd:/dev/snd ...
   829  ```
   830  
   831  By default, the container will be able to `read`, `write`, and `mknod` these devices.
   832  This can be overridden using a third `:rwm` set of options to each `--device` flag:
   833  
   834  ```console
   835  $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk  /dev/xvdc
   836  
   837  Command (m for help): q
   838  $ docker run --device=/dev/sda:/dev/xvdc:r --rm -it ubuntu fdisk  /dev/xvdc
   839  You will not be able to write the partition table.
   840  
   841  Command (m for help): q
   842  
   843  $ docker run --device=/dev/sda:/dev/xvdc:w --rm -it ubuntu fdisk  /dev/xvdc
   844      crash....
   845  
   846  $ docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk  /dev/xvdc
   847  fdisk: unable to open /dev/xvdc: Operation not permitted
   848  ```
   849  
   850  In addition to `--privileged`, the operator can have fine grain control over the
   851  capabilities using `--cap-add` and `--cap-drop`. By default, Docker has a default
   852  list of capabilities that are kept. The following table lists the Linux capability
   853  options which are allowed by default and can be dropped.
   854  
   855  | Capability Key        | Capability Description                                                                                                         |
   856  |:----------------------|:-------------------------------------------------------------------------------------------------------------------------------|
   857  | AUDIT_WRITE           | Write records to kernel auditing log.                                                                                          |
   858  | CHOWN                 | Make arbitrary changes to file UIDs and GIDs (see chown(2)).                                                                   |
   859  | DAC_OVERRIDE          | Bypass file read, write, and execute permission checks.                                                                        |
   860  | FOWNER                | Bypass permission checks on operations that normally require the file system UID of the process to match the UID of the file.  |
   861  | FSETID                | Don't clear set-user-ID and set-group-ID permission bits when a file is modified.                                              |
   862  | KILL                  | Bypass permission checks for sending signals.                                                                                  |
   863  | MKNOD                 | Create special files using mknod(2).                                                                                           |
   864  | NET_BIND_SERVICE      | Bind a socket to internet domain privileged ports (port numbers less than 1024).                                               |
   865  | NET_RAW               | Use RAW and PACKET sockets.                                                                                                    |
   866  | SETFCAP               | Set file capabilities.                                                                                                         |
   867  | SETGID                | Make arbitrary manipulations of process GIDs and supplementary GID list.                                                       |
   868  | SETPCAP               | Modify process capabilities.                                                                                                   |
   869  | SETUID                | Make arbitrary manipulations of process UIDs.                                                                                  |
   870  | SYS_CHROOT            | Use chroot(2), change root directory.                                                                                          |
   871  
   872  The next table shows the capabilities which are not granted by default and may be added.
   873  
   874  | Capability Key        | Capability Description                                                                                                         |
   875  |:----------------------|:-------------------------------------------------------------------------------------------------------------------------------|
   876  | AUDIT_CONTROL         | Enable and disable kernel auditing; change auditing filter rules; retrieve auditing status and filtering rules.                |
   877  | AUDIT_READ            | Allow reading the audit log via multicast netlink socket.                                                                      |
   878  | BLOCK_SUSPEND         | Allow preventing system suspends.                                                                                              |
   879  | BPF                   | Allow creating BPF maps, loading BPF Type Format (BTF) data, retrieve JITed code of BPF programs, and more.                    |
   880  | CHECKPOINT_RESTORE    | Allow checkpoint/restore related operations.  Introduced in kernel 5.9.                                                        |
   881  | DAC_READ_SEARCH       | Bypass file read permission checks and directory read and execute permission checks.                                           |
   882  | IPC_LOCK              | Lock memory (mlock(2), mlockall(2), mmap(2), shmctl(2)).                                                                       |
   883  | IPC_OWNER             | Bypass permission checks for operations on System V IPC objects.                                                               |
   884  | LEASE                 | Establish leases on arbitrary files (see fcntl(2)).                                                                            |
   885  | LINUX_IMMUTABLE       | Set the FS_APPEND_FL and FS_IMMUTABLE_FL i-node flags.                                                                         |
   886  | MAC_ADMIN             | Allow MAC configuration or state changes. Implemented for the Smack LSM.                                                       |
   887  | MAC_OVERRIDE          | Override Mandatory Access Control (MAC). Implemented for the Smack Linux Security Module (LSM).                                |
   888  | NET_ADMIN             | Perform various network-related operations.                                                                                    |
   889  | NET_BROADCAST         | Make socket broadcasts, and listen to multicasts.                                                                              |
   890  | PERFMON               | Allow system performance and observability privileged operations using perf_events, i915_perf and other kernel subsystems      |
   891  | SYS_ADMIN             | Perform a range of system administration operations.                                                                           |
   892  | SYS_BOOT              | Use reboot(2) and kexec_load(2), reboot and load a new kernel for later execution.                                             |
   893  | SYS_MODULE            | Load and unload kernel modules.                                                                                                |
   894  | SYS_NICE              | Raise process nice value (nice(2), setpriority(2)) and change the nice value for arbitrary processes.                          |
   895  | SYS_PACCT             | Use acct(2), switch process accounting on or off.                                                                              |
   896  | SYS_PTRACE            | Trace arbitrary processes using ptrace(2).                                                                                     |
   897  | SYS_RAWIO             | Perform I/O port operations (iopl(2) and ioperm(2)).                                                                           |
   898  | SYS_RESOURCE          | Override resource Limits.                                                                                                      |
   899  | SYS_TIME              | Set system clock (settimeofday(2), stime(2), adjtimex(2)); set real-time (hardware) clock.                                     |
   900  | SYS_TTY_CONFIG        | Use vhangup(2); employ various privileged ioctl(2) operations on virtual terminals.                                            |
   901  | SYSLOG                | Perform privileged syslog(2) operations.                                                                                       |
   902  | WAKE_ALARM            | Trigger something that will wake up the system.                                                                                |
   903  
   904  Further reference information is available on the [capabilities(7) - Linux man page](https://man7.org/linux/man-pages/man7/capabilities.7.html),
   905  and in the [Linux kernel source code](https://github.com/torvalds/linux/blob/124ea650d3072b005457faed69909221c2905a1f/include/uapi/linux/capability.h).
   906  
   907  Both flags support the value `ALL`, so to allow a container to use all capabilities
   908  except for `MKNOD`:
   909  
   910  ```console
   911  $ docker run --cap-add=ALL --cap-drop=MKNOD ...
   912  ```
   913  
   914  The `--cap-add` and `--cap-drop` flags accept capabilities to be specified with
   915  a `CAP_` prefix. The following examples are therefore equivalent:
   916  
   917  ```console
   918  $ docker run --cap-add=SYS_ADMIN ...
   919  $ docker run --cap-add=CAP_SYS_ADMIN ...
   920  ```
   921  
   922  For interacting with the network stack, instead of using `--privileged` they
   923  should use `--cap-add=NET_ADMIN` to modify the network interfaces.
   924  
   925  ```console
   926  $ docker run -it --rm  ubuntu:22.04 ip link add dummy0 type dummy
   927  
   928  RTNETLINK answers: Operation not permitted
   929  
   930  $ docker run -it --rm --cap-add=NET_ADMIN ubuntu:22.04 ip link add dummy0 type dummy
   931  ```
   932  
   933  To mount a FUSE based filesystem, you need to combine both `--cap-add` and
   934  `--device`:
   935  
   936  ```console
   937  $ docker run --rm -it --cap-add SYS_ADMIN sshfs sshfs sven@10.10.10.20:/home/sven /mnt
   938  
   939  fuse: failed to open /dev/fuse: Operation not permitted
   940  
   941  $ docker run --rm -it --device /dev/fuse sshfs sshfs sven@10.10.10.20:/home/sven /mnt
   942  
   943  fusermount: mount failed: Operation not permitted
   944  
   945  $ docker run --rm -it --cap-add SYS_ADMIN --device /dev/fuse sshfs
   946  
   947  # sshfs sven@10.10.10.20:/home/sven /mnt
   948  The authenticity of host '10.10.10.20 (10.10.10.20)' can't be established.
   949  ECDSA key fingerprint is 25:34:85:75:25:b0:17:46:05:19:04:93:b5:dd:5f:c6.
   950  Are you sure you want to continue connecting (yes/no)? yes
   951  sven@10.10.10.20's password:
   952  
   953  root@30aa0cfaf1b5:/# ls -la /mnt/src/docker
   954  
   955  total 1516
   956  drwxrwxr-x 1 1000 1000   4096 Dec  4 06:08 .
   957  drwxrwxr-x 1 1000 1000   4096 Dec  4 11:46 ..
   958  -rw-rw-r-- 1 1000 1000     16 Oct  8 00:09 .dockerignore
   959  -rwxrwxr-x 1 1000 1000    464 Oct  8 00:09 .drone.yml
   960  drwxrwxr-x 1 1000 1000   4096 Dec  4 06:11 .git
   961  -rw-rw-r-- 1 1000 1000    461 Dec  4 06:08 .gitignore
   962  ....
   963  ```
   964  
   965  The default seccomp profile will adjust to the selected capabilities, in order to allow
   966  use of facilities allowed by the capabilities, so you should not have to adjust this.
   967  
   968  ## Overriding image defaults
   969  
   970  When you build an image from a [Dockerfile](https://docs.docker.com/reference/dockerfile/),
   971  or when committing it, you can set a number of default parameters that take
   972  effect when the image starts up as a container. When you run an image, you can
   973  override those defaults using flags for the `docker run` command.
   974  
   975  - [Default entrypoint](#default-entrypoint)
   976  - [Default command and options](#default-command-and-options)
   977  - [Expose ports](#exposed-ports)
   978  - [Environment variables](#environment-variables)
   979  - [Healthcheck](#healthchecks)
   980  - [User](#user)
   981  - [Working directory](#working-directory)
   982  
   983  ### Default command and options
   984  
   985  The command syntax for `docker run` supports optionally specifying commands and
   986  arguments to the container's entrypoint, represented as `[COMMAND]` and
   987  `[ARG...]` in the following synopsis example:
   988  
   989  ```console
   990  $ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]
   991  ```
   992  
   993  This command is optional because whoever created the `IMAGE` may have already
   994  provided a default `COMMAND`, using the Dockerfile `CMD` instruction. When you
   995  run a container, you can override that `CMD` instruction just by specifying a
   996  new `COMMAND`.
   997  
   998  If the image also specifies an `ENTRYPOINT` then the `CMD` or `COMMAND`
   999  get appended as arguments to the `ENTRYPOINT`.
  1000  
  1001  ### Default entrypoint
  1002  
  1003  ```text
  1004  --entrypoint="": Overwrite the default entrypoint set by the image
  1005  ```
  1006  
  1007  The entrypoint refers to the default executable that's invoked when you run a
  1008  container. A container's entrypoint is defined using the Dockerfile
  1009  `ENTRYPOINT` instruction. It's similar to specifying a default command because
  1010  it specifies, but the difference is that you need to pass an explicit flag to
  1011  override the entrypoint, whereas you can override default commands with
  1012  positional arguments. The defines a container's default behavior, with the idea
  1013  that when you set an entrypoint you can run the container *as if it were that
  1014  binary*, complete with default options, and you can pass in more options as
  1015  commands. But there are cases where you may want to run something else inside
  1016  the container. This is when overriding the default entrypoint at runtime comes
  1017  in handy, using the `--entrypoint` flag for the `docker run` command.
  1018  
  1019  The `--entrypoint` flag expects a string value, representing the name or path
  1020  of the binary that you want to invoke when the container starts. The following
  1021  example shows you how to run a Bash shell in a container that has been set up
  1022  to automatically run some other binary (like `/usr/bin/redis-server`):
  1023  
  1024  ```console
  1025  $ docker run -it --entrypoint /bin/bash example/redis
  1026  ```
  1027  
  1028  The following examples show how to pass additional parameters to the custom
  1029  entrypoint, using the positional command arguments:
  1030  
  1031  ```console
  1032  $ docker run -it --entrypoint /bin/bash example/redis -c ls -l
  1033  $ docker run -it --entrypoint /usr/bin/redis-cli example/redis --help
  1034  ```
  1035  
  1036  You can reset a containers entrypoint by passing an empty string, for example:
  1037  
  1038  ```console
  1039  $ docker run -it --entrypoint="" mysql bash
  1040  ```
  1041  
  1042  > **Note**
  1043  >
  1044  > Passing `--entrypoint` clears out any default command set on the image. That
  1045  > is, any `CMD` instruction in the Dockerfile used to build it.
  1046  
  1047  ### Exposed ports
  1048  
  1049  By default, when you run a container, none of the container's ports are exposed
  1050  to the host. This means you won't be able to access any ports that the
  1051  container might be listening on. To make a container's ports accessible from
  1052  the host, you need to publish the ports.
  1053  
  1054  You can start the container with the `-P` or `-p` flags to expose its ports:
  1055  
  1056  - The `-P` (or `--publish-all`) flag publishes all the exposed ports to the
  1057    host. Docker binds each exposed port to a random port on the host.
  1058  
  1059    The `-P` flag only publishes port numbers that are explicitly flagged as
  1060    exposed, either using the Dockerfile `EXPOSE` instruction or the `--expose`
  1061    flag for the `docker run` command.
  1062  
  1063  - The `-p` (or `--publish`) flag lets you explicitly map a single port or range
  1064    of ports in the container to the host.
  1065  
  1066  The port number inside the container (where the service listens) doesn't need
  1067  to match the port number published on the outside of the container (where
  1068  clients connect). For example, inside the container an HTTP service might be
  1069  listening on port 80. At runtime, the port might be bound to 42800 on the host.
  1070  To find the mapping between the host ports and the exposed ports, use the
  1071  `docker port` command.
  1072  
  1073  ### Environment variables
  1074  
  1075  Docker automatically sets some environment variables when creating a Linux
  1076  container. Docker doesn't set any environment variables when creating a Windows
  1077  container.
  1078  
  1079  The following environment variables are set for Linux containers:
  1080  
  1081  | Variable   | Value                                                                                                |
  1082  |:-----------|:-----------------------------------------------------------------------------------------------------|
  1083  | `HOME`     | Set based on the value of `USER`                                                                     |
  1084  | `HOSTNAME` | The hostname associated with the container                                                           |
  1085  | `PATH`     | Includes popular directories, such as `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin` |
  1086  | `TERM`     | `xterm` if the container is allocated a pseudo-TTY                                                   |
  1087  
  1088  
  1089  Additionally, you can set any environment variable in the container by using
  1090  one or more `-e` flags. You can even override the variables mentioned above, or
  1091  variables defined using a Dockerfile `ENV` instruction when building the image.
  1092  
  1093  If the you name an environment variable without specifying a value, the current
  1094  value of the named variable on the host is propagated into the container's
  1095  environment:
  1096  
  1097  ```console
  1098  $ export today=Wednesday
  1099  $ docker run -e "deep=purple" -e today --rm alpine env
  1100  
  1101  PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
  1102  HOSTNAME=d2219b854598
  1103  deep=purple
  1104  today=Wednesday
  1105  HOME=/root
  1106  ```
  1107  
  1108  ```powershell
  1109  PS C:\> docker run --rm -e "foo=bar" microsoft/nanoserver cmd /s /c set
  1110  ALLUSERSPROFILE=C:\ProgramData
  1111  APPDATA=C:\Users\ContainerAdministrator\AppData\Roaming
  1112  CommonProgramFiles=C:\Program Files\Common Files
  1113  CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
  1114  CommonProgramW6432=C:\Program Files\Common Files
  1115  COMPUTERNAME=C2FAEFCC8253
  1116  ComSpec=C:\Windows\system32\cmd.exe
  1117  foo=bar
  1118  LOCALAPPDATA=C:\Users\ContainerAdministrator\AppData\Local
  1119  NUMBER_OF_PROCESSORS=8
  1120  OS=Windows_NT
  1121  Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Users\ContainerAdministrator\AppData\Local\Microsoft\WindowsApps
  1122  PATHEXT=.COM;.EXE;.BAT;.CMD
  1123  PROCESSOR_ARCHITECTURE=AMD64
  1124  PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 62 Stepping 4, GenuineIntel
  1125  PROCESSOR_LEVEL=6
  1126  PROCESSOR_REVISION=3e04
  1127  ProgramData=C:\ProgramData
  1128  ProgramFiles=C:\Program Files
  1129  ProgramFiles(x86)=C:\Program Files (x86)
  1130  ProgramW6432=C:\Program Files
  1131  PROMPT=$P$G
  1132  PUBLIC=C:\Users\Public
  1133  SystemDrive=C:
  1134  SystemRoot=C:\Windows
  1135  TEMP=C:\Users\ContainerAdministrator\AppData\Local\Temp
  1136  TMP=C:\Users\ContainerAdministrator\AppData\Local\Temp
  1137  USERDOMAIN=User Manager
  1138  USERNAME=ContainerAdministrator
  1139  USERPROFILE=C:\Users\ContainerAdministrator
  1140  windir=C:\Windows
  1141  ```
  1142  
  1143  ### Healthchecks
  1144  
  1145  The following flags for the `docker run` command let you control the parameters
  1146  for container healthchecks:
  1147  
  1148  | Option                     | Description                                                                            |
  1149  |:---------------------------|:---------------------------------------------------------------------------------------|
  1150  | `--health-cmd`             | Command to run to check health                                                         |
  1151  | `--health-interval`        | Time between running the check                                                         |
  1152  | `--health-retries`         | Consecutive failures needed to report unhealthy                                        |
  1153  | `--health-timeout`         | Maximum time to allow one check to run                                                 |
  1154  | `--health-start-period`    | Start period for the container to initialize before starting health-retries countdown  |
  1155  | `--health-start-interval`  | Time between running the check during the start period                                 |
  1156  | `--no-healthcheck`         | Disable any container-specified `HEALTHCHECK`                                          |
  1157  
  1158  Example:
  1159  
  1160  ```console
  1161  $ docker run --name=test -d \
  1162      --health-cmd='stat /etc/passwd || exit 1' \
  1163      --health-interval=2s \
  1164      busybox sleep 1d
  1165  $ sleep 2; docker inspect --format='{{.State.Health.Status}}' test
  1166  healthy
  1167  $ docker exec test rm /etc/passwd
  1168  $ sleep 2; docker inspect --format='{{json .State.Health}}' test
  1169  {
  1170    "Status": "unhealthy",
  1171    "FailingStreak": 3,
  1172    "Log": [
  1173      {
  1174        "Start": "2016-05-25T17:22:04.635478668Z",
  1175        "End": "2016-05-25T17:22:04.7272552Z",
  1176        "ExitCode": 0,
  1177        "Output": "  File: /etc/passwd\n  Size: 334       \tBlocks: 8          IO Block: 4096   regular file\nDevice: 32h/50d\tInode: 12          Links: 1\nAccess: (0664/-rw-rw-r--)  Uid: (    0/    root)   Gid: (    0/    root)\nAccess: 2015-12-05 22:05:32.000000000\nModify: 2015..."
  1178      },
  1179      {
  1180        "Start": "2016-05-25T17:22:06.732900633Z",
  1181        "End": "2016-05-25T17:22:06.822168935Z",
  1182        "ExitCode": 0,
  1183        "Output": "  File: /etc/passwd\n  Size: 334       \tBlocks: 8          IO Block: 4096   regular file\nDevice: 32h/50d\tInode: 12          Links: 1\nAccess: (0664/-rw-rw-r--)  Uid: (    0/    root)   Gid: (    0/    root)\nAccess: 2015-12-05 22:05:32.000000000\nModify: 2015..."
  1184      },
  1185      {
  1186        "Start": "2016-05-25T17:22:08.823956535Z",
  1187        "End": "2016-05-25T17:22:08.897359124Z",
  1188        "ExitCode": 1,
  1189        "Output": "stat: can't stat '/etc/passwd': No such file or directory\n"
  1190      },
  1191      {
  1192        "Start": "2016-05-25T17:22:10.898802931Z",
  1193        "End": "2016-05-25T17:22:10.969631866Z",
  1194        "ExitCode": 1,
  1195        "Output": "stat: can't stat '/etc/passwd': No such file or directory\n"
  1196      },
  1197      {
  1198        "Start": "2016-05-25T17:22:12.971033523Z",
  1199        "End": "2016-05-25T17:22:13.082015516Z",
  1200        "ExitCode": 1,
  1201        "Output": "stat: can't stat '/etc/passwd': No such file or directory\n"
  1202      }
  1203    ]
  1204  }
  1205  ```
  1206  
  1207  The health status is also displayed in the `docker ps` output.
  1208  
  1209  ### User
  1210  
  1211  The default user within a container is `root` (uid = 0). You can set a default
  1212  user to run the first process with the Dockerfile `USER` instruction. When
  1213  starting a container, you can override the `USER` instruction by passing the
  1214  `-u` option.
  1215  
  1216  ```text
  1217  -u="", --user="": Sets the username or UID used and optionally the groupname or GID for the specified command.
  1218  ```
  1219  
  1220  The followings examples are all valid:
  1221  
  1222  ```text
  1223  --user=[ user | user:group | uid | uid:gid | user:gid | uid:group ]
  1224  ```
  1225  
  1226  > **Note**
  1227  >
  1228  > If you pass a numeric user ID, it must be in the range of 0-2147483647. If
  1229  > you pass a username, the user must exist in the container.
  1230  
  1231  ### Working directory
  1232  
  1233  The default working directory for running binaries within a container is the
  1234  root directory (`/`). The default working directory of an image is set using
  1235  the Dockerfile `WORKDIR` command. You can override the default working
  1236  directory for an image using the `-w` (or `--workdir`) flag for the `docker
  1237  run` command:
  1238  
  1239  ```text
  1240  $ docker run --rm -w /my/workdir alpine pwd
  1241  /my/workdir
  1242  ```
  1243  
  1244  If the directory doesn't already exist in the container, it's created.