Movatterモバイル変換


[0]ホーム

URL:


Contact support
Contact support
Reference

docker container run

DescriptionCreate and run a new container from an image
Usagedocker container run [OPTIONS] IMAGE [COMMAND] [ARG...]
Aliases
An alias is a short or memorable alternative for a longer command.
docker run

Description

Thedocker run command runs a command in a new container, pulling the image if needed and starting the container.

You can restart a stopped container with all its previous changes intact usingdocker start.Usedocker ps -a to view a list of all containers, including those that are stopped.

Options

OptionDefaultDescription
--add-hostAdd a custom host-to-IP mapping (host:ip)
--annotationAPI 1.43+Add an annotation to the container (passed through to the OCI runtime)
-a, --attachAttach to STDIN, STDOUT or STDERR
--blkio-weightBlock IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
--blkio-weight-deviceBlock IO weight (relative device weight)
--cap-addAdd Linux capabilities
--cap-dropDrop Linux capabilities
--cgroup-parentOptional parent cgroup for the container
--cgroupnsAPI 1.41+Cgroup namespace to use (host|private)
'host': Run the container in the Docker host's cgroup namespace
'private': Run the container in its own private cgroup namespace
'': Use the cgroup namespace as configured by the
default-cgroupns-mode option on the daemon (default)
--cidfileWrite the container ID to the file
--cpu-countCPU count (Windows only)
--cpu-percentCPU percent (Windows only)
--cpu-periodLimit CPU CFS (Completely Fair Scheduler) period
--cpu-quotaLimit CPU CFS (Completely Fair Scheduler) quota
--cpu-rt-periodAPI 1.25+Limit CPU real-time period in microseconds
--cpu-rt-runtimeAPI 1.25+Limit CPU real-time runtime in microseconds
-c, --cpu-sharesCPU shares (relative weight)
--cpusAPI 1.25+Number of CPUs
--cpuset-cpusCPUs in which to allow execution (0-3, 0,1)
--cpuset-memsMEMs in which to allow execution (0-3, 0,1)
-d, --detachRun container in background and print container ID
--detach-keysOverride the key sequence for detaching a container
--deviceAdd a host device to the container
--device-cgroup-ruleAdd a rule to the cgroup allowed devices list
--device-read-bpsLimit read rate (bytes per second) from a device
--device-read-iopsLimit read rate (IO per second) from a device
--device-write-bpsLimit write rate (bytes per second) to a device
--device-write-iopsLimit write rate (IO per second) to a device
--disable-content-trusttrueSkip image verification
--dnsSet custom DNS servers
--dns-optionSet DNS options
--dns-searchSet custom DNS search domains
--domainnameContainer NIS domain name
--entrypointOverwrite the default ENTRYPOINT of the image
-e, --envSet environment variables
--env-fileRead in a file of environment variables
--exposeExpose a port or a range of ports
--gpusAPI 1.40+GPU devices to add to the container ('all' to pass all GPUs)
--group-addAdd additional groups to join
--health-cmdCommand to run to check health
--health-intervalTime between running the check (ms|s|m|h) (default 0s)
--health-retriesConsecutive failures needed to report unhealthy
--health-start-intervalAPI 1.44+Time between running the check during the start period (ms|s|m|h) (default 0s)
--health-start-periodAPI 1.29+Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
--health-timeoutMaximum time to allow one check to run (ms|s|m|h) (default 0s)
--helpPrint usage
-h, --hostnameContainer host name
--initAPI 1.25+Run an init inside the container that forwards signals and reaps processes
-i, --interactiveKeep STDIN open even if not attached
--io-maxbandwidthMaximum IO bandwidth limit for the system drive (Windows only)
--io-maxiopsMaximum IOps limit for the system drive (Windows only)
--ipIPv4 address (e.g., 172.30.100.104)
--ip6IPv6 address (e.g., 2001:db8::33)
--ipcIPC mode to use
--isolationContainer isolation technology
--kernel-memoryKernel memory limit
-l, --labelSet meta data on a container
--label-fileRead in a line delimited file of labels
--linkAdd link to another container
--link-local-ipContainer IPv4/IPv6 link-local addresses
--log-driverLogging driver for the container
--log-optLog driver options
--mac-addressContainer MAC address (e.g., 92:d0:c6:0a:29:33)
-m, --memoryMemory limit
--memory-reservationMemory soft limit
--memory-swapSwap limit equal to memory plus swap: '-1' to enable unlimited swap
--memory-swappiness-1Tune container memory swappiness (0 to 100)
--mountAttach a filesystem mount to the container
--nameAssign a name to the container
--networkConnect a container to a network
--network-aliasAdd network-scoped alias for the container
--no-healthcheckDisable any container-specified HEALTHCHECK
--oom-kill-disableDisable OOM Killer
--oom-score-adjTune host's OOM preferences (-1000 to 1000)
--pidPID namespace to use
--pids-limitTune container pids limit (set -1 for unlimited)
--platformAPI 1.32+Set platform if server is multi-platform capable
--privilegedGive extended privileges to this container
-p, --publishPublish a container's port(s) to the host
-P, --publish-allPublish all exposed ports to random ports
--pullmissingPull image before running (always,missing,never)
-q, --quietSuppress the pull output
--read-onlyMount the container's root filesystem as read only
--restartnoRestart policy to apply when a container exits
--rmAutomatically remove the container and its associated anonymous volumes when it exits
--runtimeRuntime to use for this container
--security-optSecurity Options
--shm-sizeSize of /dev/shm
--sig-proxytrueProxy received signals to the process
--stop-signalSignal to stop the container
--stop-timeoutAPI 1.25+Timeout (in seconds) to stop a container
--storage-optStorage driver options for the container
--sysctlSysctl options
--tmpfsMount a tmpfs directory
-t, --ttyAllocate a pseudo-TTY
--ulimitUlimit options
--use-api-socketBind mount Docker API socket and required auth
-u, --userUsername or UID (format: <name|uid>[:<group|gid>])
--usernsUser namespace to use
--utsUTS namespace to use
-v, --volumeBind mount a volume
--volume-driverOptional volume driver for the container
--volumes-fromMount volumes from the specified container(s)
-w, --workdirWorking directory inside the container

Examples

Assign name (--name)

The--name flag lets you specify a custom identifier for a container. Thefollowing example runs a container namedtest using thenginx:alpine imageindetached mode.

$ docker run --nametest -d nginx:alpine4bed76d3ad428b889c56c1ecc2bf2ed95cb08256db22dc5ef5863e1d03252a19$ docker psCONTAINER ID   IMAGE          COMMAND                  CREATED        STATUS                  PORTS     NAMES4bed76d3ad42   nginx:alpine   "/docker-entrypoint.…"   1 second ago   Up Less than a second   80/tcp    test

You can reference the container by name with other commands. For example, thefollowing commands stop and remove a container namedtest:

$ docker stoptesttest$ docker rmtesttest

If you don't specify a custom name using the--name flag, the daemon assignsa randomly generated name, such asvibrant_cannon, to the container. Using acustom-defined name provides the benefit of having an easy-to-remember ID for acontainer.

Moreover, if you connect the container to a user-defined bridge network, othercontainers on the same network can refer to the container by name via DNS.

$ docker network create mynetcb79f45948d87e389e12013fa4d969689ed2c3316985dd832a43aaec9a0fe394$ docker run --nametest --net mynet -d nginx:alpine58df6ecfbc2ad7c42d088ed028d367f9e22a5f834d7c74c66c0ab0485626c32a$ docker run --net mynet busybox:latest pingtestPING test (172.18.0.2): 56 data bytes64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.073 ms64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.411 ms64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.319 ms64 bytes from 172.18.0.2: seq=3 ttl=64 time=0.383 ms...

Capture container ID (--cidfile)

To help with automation, you can have Docker write the container ID out to afile of your choosing. This is similar to how some programs might write outtheir process ID to a file (you might've seen them as PID files):

$ docker run --cidfile /tmp/docker_test.cid ubuntuecho"test"

This creates a container and printstest to the console. Thecidfileflag makes Docker attempt to create a new file and write the container ID to it.If the file exists already, Docker returns an error. Docker closes thisfile whendocker run exits.

PID settings (--pid)

--pid=""  : Set the PID (Process) Namespace mode for the container,             'container:<name|id>': joins another container's PID namespace             'host': use the host's PID namespace inside the container

By default, all containers have the PID namespace enabled.

PID namespace provides separation of processes. The PID Namespace removes theview of the system processes, and allows process ids to be reused includingPID 1.

In certain cases you want your container to share the host's process namespace,allowing processes within the container to see all of the processes on thesystem. For example, you could build a container with debugging tools likestrace orgdb, but want to use these tools when debugging processes withinthe container.

Example: run htop inside a container

To runhtop in a container that shares the process namespac of the host:

  1. Run an alpine container with the--pid=host option:

    $ docker run --rm -it --pid=host alpine
  2. Installhtop in the container:

    / # apk add --quiet htop
  3. Invoke thehtop command.

    / # htop

Example, join another container's PID namespace

Joining another container's PID namespace can be useful for debugging thatcontainer.

  1. Start a container running a Redis server:

    $ docker run --rm --name my-nginx -d nginx:alpine
  2. Run an Alpine container that attaches the--pid namespace to themy-nginx container:

    $ docker run --rm -it --pid=container:my-nginx\  --cap-add SYS_PTRACE \  --security-opt seccomp=unconfined \  alpine
  3. Installstrace in the Alpine container:

    / # apk add strace
  4. Attach to process 1, the process ID of themy-nginx container:

    / # strace -p 1strace: Process 1 attached

Disable namespace remapping for a container (--userns)

If you enable user namespaces on the daemon,all containers are started with user namespaces enabled by default.To disable user namespace remapping for a specific container,you can set the--userns flag tohost.

docker run --userns=host hello-world

host is the only valid value for the--userns flag.

For more information, refer toIsolate containers with a user namespace.

UTS settings (--uts)

--uts=""  : Set the UTS namespace mode for the container            'host': use the host's UTS namespace inside the container

The UTS namespace is for setting the hostname and the domain that's visible torunning processes in that namespace. By default, all containers, includingthose with--network=host, have their own UTS namespace. Setting--uts tohost results in the container using the same UTS namespace as the host.

Note

Docker disallows combining the--hostname and--domainname flags with--uts=host. This is to prevent containers running in the host's UTSnamespace from attempting to change the hosts' configuration.

You may wish to share the UTS namespace with the host if you would like thehostname of the container to change as the hostname of the host changes. A moreadvanced use case would be changing the host's hostname from a container.

IPC settings (--ipc)

--ipc="MODE"  : Set the IPC mode for the container

The--ipc flag accepts the following values:

ValueDescription
""Use daemon's default.
"none"Own private IPC namespace, with /dev/shm not mounted.
"private"Own private IPC namespace.
"shareable"Own private IPC namespace, with a possibility to share it with other containers.
"container:<name-or-ID>"Join another ("shareable") container's IPC namespace.
"host"Use the host system's IPC namespace.

If not specified, daemon default is used, which can either be"private"or"shareable", depending on the daemon version and configuration.

System V interprocess communication (IPC)namespaces provide separation of named shared memory segments, semaphores andmessage queues.

Shared memory segments are used to accelerate inter-process communication atmemory speed, rather than through pipes or through the network stack. Sharedmemory is commonly used by databases and custom-built (typically C/OpenMPI,C++/using boost libraries) high performance applications for scientificcomputing and financial services industries. If these types of applicationsare broken into multiple containers, you might need to share the IPC mechanismsof the containers, using"shareable" mode for the main (i.e. "donor")container, and"container:<donor-name-or-ID>" for other containers.

Escalate container privileges (--privileged)

The--privileged flag gives the following capabilities to a container:

  • Enables all Linux kernel capabilities
  • Disables the default seccomp profile
  • Disables the default AppArmor profile
  • Disables the SELinux process label
  • Grants access to all host devices
  • Makes/sys read-write
  • Makes cgroups mounts read-write

In other words, the container can then do almost everything that the host cando. This flag exists to allow special use-cases, like running Docker withinDocker.

Warning

Use the--privileged flag with caution.A container with--privileged is not a securely sandboxed process.Containers in this mode can get a root shell on the hostand take control over the system.

For most use cases, this flag should not be the preferred solution.If your container requires escalated privileges,you should prefer to explicitly grant the necessary permissions,for example by adding individual kernel capabilities with--cap-add.

For more information, seeRuntime privilege and Linux capabilities

The following example doesn't work, because by default, Docker drops mostpotentially dangerous kernel capabilities, includingCAP_SYS_ADMIN(which isrequired to mount filesystems).

$ docker run -t -i --rm ubuntu bashroot@bc338942ef20:/# mount -t tmpfs none /mntmount: permission denied

It works when you add the--privileged flag:

$ docker run -t -i --privileged ubuntu bashroot@50e3f57e16e6:/# mount -t tmpfs none /mntroot@50e3f57e16e6:/# df -hFilesystem      Size  Used Avail Use% Mounted onnone            1.9G     0  1.9G   0% /mnt

Set working directory (-w, --workdir)

$ docker run -w /path/to/dir/ ubuntupwd

The-w option runs the command executed inside the directory specified, in this example,/path/to/dir/. If the path doesn't exist, Docker creates it inside the container.

Set storage driver options per container (--storage-opt)

$ docker run -it --storage-optsize=120G fedora /bin/bash

This (size) constraints the container filesystem size to 120G at creation time.This option is only available for thebtrfs,overlay2,windowsfilter,andzfs storage drivers.

For theoverlay2 storage driver, the size option is only available if thebacking filesystem isxfs and mounted with thepquota mount option.Under these conditions, you can pass any size less than the backing filesystem size.

For thewindowsfilter,btrfs, andzfs storage drivers, you cannot pass asize less than the Default BaseFS Size.

Mount tmpfs (--tmpfs)

The--tmpfs flag lets you create atmpfs mount.

The options that you can pass to--tmpfs are identical to the Linuxmount -t tmpfs -o command. The following example mounts an emptytmpfs into thecontainer with therw,noexec,nosuid,size=65536k options.

$ docker run -d --tmpfs /run:rw,noexec,nosuid,size=65536k my_image

For more information, seetmpfs mounts.

Mount volume (-v)

$ docker  run  -v$(pwd):$(pwd) -w$(pwd) -i -t  ubuntupwd

The example above mounts the current directory into the container at the same pathusing the-v flag, sets it as the working directory, and then runs thepwd command inside the container.

As of Docker Engine version 23, you can use relative paths on the host.

$ docker  run  -v ./content:/content -w /content -i -t  ubuntupwd

The example above mounts thecontent directory in the current directory into the container at the/content path using the-v flag, sets it as the working directory, and thenruns thepwd command inside the container.

$ docker run -v /doesnt/exist:/foo -w /foo -i -t ubuntu bash

When the host directory of a bind-mounted volume doesn't exist, Dockerautomatically creates this directory on the host for you. In theexample above, Docker creates the/doesnt/existfolder before starting your container.

Mount volume read-only (--read-only)

$ docker run --read-only -v /icanwrite busybox touch /icanwrite/here

You can use volumes in combination with the--read-only flag to control wherea container writes files. The--read-only flag mounts the container's rootfilesystem as read only prohibiting writes to locations other than thespecified volumes for the container.

$ docker run -t -i -v /var/run/docker.sock:/var/run/docker.sock -v /path/to/static-docker-binary:/usr/bin/docker busybox sh

By bind-mounting the Docker Unix socket and statically linked Dockerbinary (refer toget the Linux binary),you give the container the full access to create and manipulate the host'sDocker daemon.

On Windows, you must specify the paths using Windows-style path semantics.

PSC:\>dockerrun-vc:\foo:c:\destmicrosoft/nanoservercmd/s/ctypec:\dest\somefile.txtContentsoffilePSC:\>dockerrun-vc:\foo:d:microsoft/nanoservercmd/s/ctyped:\somefile.txtContentsoffile

The following examples fails when using Windows-based containers, as thedestination of a volume or bind mount inside the container must be one of:a non-existing or empty directory; or a drive other thanC:. Further, the sourceof a bind mount must be a local directory, not a file.

netusez:\\remotemachine\sharedockerrun-vz:\foo:c:\dest...dockerrun-v\\uncpath\to\directory:c:\dest...dockerrun-vc:\foo\somefile.txt:c:\dest...dockerrun-vc:\foo:c:...dockerrun-vc:\foo:c:\existing-directory-with-contents...

For in-depth information about volumes, refer tomanage data in containers

Add bind mounts or volumes using the --mount flag

The--mount flag allows you to mount volumes, host-directories, andtmpfsmounts in a container.

The--mount flag supports most options supported by the-v or the--volume flag, but uses a different syntax. For in-depth information on the--mount flag, and a comparison between--volume and--mount, refer toBind mounts.

Even though there is no plan to deprecate--volume, usage of--mount is recommended.

Examples:

$ docker run --read-only --mounttype=volume,target=/icanwrite busybox touch /icanwrite/here
$ docker run -t -i --mounttype=bind,src=/data,dst=/data busybox sh

Publish or expose port (-p, --expose)

$ docker run -p 127.0.0.1:80:8080/tcp nginx:alpine

This binds port8080 of the container to TCP port80 on127.0.0.1 of thehost. You can also specifyudp andsctp ports. TheNetworking overviewpage explains in detail how to publish portswith Docker.

Note

If you don't specify an IP address (i.e.,-p 80:80 instead of-p 127.0.0.1:80:80) when publishing a container's ports, Docker publishes theport on all interfaces (address0.0.0.0) by default. These ports areexternally accessible. This also applies if you configured UFW to block thisspecific port, as Docker manages its own iptables rules.Readmore

$ docker run --expose80 nginx:alpine

This exposes port80 of the container without publishing the port to the hostsystem's interfaces.

Publish all exposed ports (-P, --publish-all)

$ docker run -P nginx:alpine

The-P, or--publish-all, flag publishes all the exposed ports to the host.Docker binds each exposed port to a random port on the host.

The-P flag only publishes port numbers that are explicitly flagged asexposed, either using the DockerfileEXPOSE instruction or the--exposeflag for thedocker run command.

The range of ports are within anephemeral port range defined by/proc/sys/net/ipv4/ip_local_port_range. Use the-p flag to explicitly map asingle port or range of ports.

Set the pull policy (--pull)

Use the--pull flag to set the image pull policy when creating (and running)the container.

The--pull flag can take one of these values:

ValueDescription
missing (default)Pull the image if it was not found in the image cache, or use the cached image otherwise.
neverDo not pull the image, even if it's missing, and produce an error if the image does not exist in the image cache.
alwaysAlways perform a pull before creating the container.

When creating (and running) a container from an image, the daemon checks if theimage exists in the local image cache. If the image is missing, an error isreturned to the CLI, allowing it to initiate a pull.

The default (missing) is to only pull the image if it's not present in thedaemon's image cache. This default allows you to run images that only existlocally (for example, images you built from a Dockerfile, but that have notbeen pushed to a registry), and reduces networking.

Thealways option always initiates a pull before creating the container. Thisoption makes sure the image is up-to-date, and prevents you from using outdatedimages, but may not be suitable in situations where you want to test a locallybuilt image before pushing (as pulling the image overwrites the existing imagein the image cache).

Thenever option disables (implicit) pulling images when creating containers,and only uses images that are available in the image cache. If the specifiedimage is not found, an error is produced, and the container is not created.This option is useful in situations where networking is not available, or toprevent images from being pulled implicitly when creating containers.

The following example showsdocker run with the--pull=never option set,which produces en error as the image is missing in the image-cache:

$ docker run --pull=never hello-worlddocker: Error response from daemon: No such image: hello-world:latest.

Set environment variables (-e, --env, --env-file)

$ docker run -e MYVAR1 --envMYVAR2=foo --env-file ./env.list ubuntu bash

Use the-e,--env, and--env-file flags to set simple (non-array)environment variables in the container you're running, or overwrite variablesdefined in the Dockerfile of the image you're running.

You can define the variable and its value when running the container:

$ docker run --envVAR1=value1 --envVAR2=value2 ubuntu env| grep VARVAR1=value1VAR2=value2

You can also use variables exported to your local environment:

export VAR1=value1export VAR2=value2$ docker run --env VAR1 --env VAR2 ubuntu env| grep VARVAR1=value1VAR2=value2

When running the command, the Docker CLI client checks the value the variablehas in your local environment and passes it to the container.If no= is provided and that variable isn't exported in your localenvironment, the variable is unset in the container.

You can also load the environment variables from a file. This file should usethe syntax<variable>=value (which sets the variable to the given value) or<variable> (which takes the value from the local environment), and# forcomments. Lines beginning with# are treated as line comments and areignored, whereas a# appearing anywhere else in a line is treated as part ofthe variable value.

$ cat env.list# This is a commentVAR1=value1VAR2=value2USER$ docker run --env-file env.list ubuntu env| grep -E'VAR|USER'VAR1=value1VAR2=value2USER=jonzeolla

Set metadata on container (-l, --label, --label-file)

A label is akey=value pair that applies metadata to a container. To label a container with two labels:

$ docker run -l my-label --label com.example.foo=bar ubuntu bash

Themy-label key doesn't specify a value so the label defaults to an emptystring (""). To add multiple labels, repeat the label flag (-l or--label).

Thekey=value must be unique to avoid overwriting the label value. If youspecify labels with identical keys but different values, each subsequent valueoverwrites the previous. Docker uses the lastkey=value you supply.

Use the--label-file flag to load multiple labels from a file. Delimit eachlabel in the file with an EOL mark. The example below loads labels from alabels file in the current directory:

$ docker run --label-file ./labels ubuntu bash

The label-file format is similar to the format for loading environmentvariables. (Unlike environment variables, labels are not visible to processesrunning inside a container.) The following example shows a label-fileformat:

com.example.label1="a label"# this is a commentcom.example.label2=another\ labelcom.example.label3

You can load multiple label-files by supplying multiple--label-file flags.

For additional information on working with labels, seeLabels.

Connect a container to a network (--network)

To start a container and connect it to a network, use the--network option.

If you want to add a running container to a network use thedocker network connect subcommand.

You can connect multiple containers to the same network. Once connected, thecontainers can communicate using only another container's IP addressor name. Foroverlay networks or custom plugins that support multi-hostconnectivity, containers connected to the same multi-host network but launchedfrom different Engines can also communicate in this way.

Note

The default bridge network only allows containers to communicate with each other usinginternal IP addresses. User-created bridge networks provide DNS resolution betweencontainers using container names.

You can disconnect a container from a network using thedocker network disconnect command.

The following commands create a network namedmy-net and add abusybox containerto themy-net network.

$ docker network create my-net$ docker run -itd --network=my-net busybox

You can also choose the IP addresses for the container with--ip and--ip6flags when you start the container on a user-defined network. To assign astatic IP to containers, you must specify subnet block for the network.

$ docker network create --subnet 192.0.2.0/24 my-net$ docker run -itd --network=my-net --ip=192.0.2.69 busybox

To connect the container to more than one network, repeat the--network option.

$ docker network create --subnet 192.0.2.0/24 my-net1$ docker network create --subnet 192.0.3.0/24 my-net2$ docker run -itd --network=my-net1 --network=my-net2 busybox

To specify options when connecting to more than one network, use the extended syntaxfor the--network flag. Comma-separated options that can be specified in the extended--network syntax are:

OptionTop-level EquivalentDescription
nameThe name of the network (mandatory)
alias--network-aliasAdd network-scoped alias for the container
ip--ipIPv4 address (e.g., 172.30.100.104)
ip6--ip6IPv6 address (e.g., 2001:db8::33)
mac-address--mac-addressContainer MAC address (e.g., 92:d0:c6:0a:29:33)
link-local-ip--link-local-ipContainer IPv4/IPv6 link-local addresses
driver-optdocker network connect --driver-optNetwork driver options
gw-priorityHighest gw-priority provides the default gateway. Accepts positive and negative values.
$ docker network create --subnet 192.0.2.0/24 my-net1$ docker network create --subnet 192.0.3.0/24 my-net2$ docker run -itd --network=name=my-net1,ip=192.0.2.42 --network=name=my-net2,ip=192.0.3.42 busybox

sysctl settings that start withnet.ipv4.,net.ipv6. ornet.mpls. can beset per-interface usingdriver-opt labelcom.docker.network.endpoint.sysctls.The interface name must be the stringIFNAME.

To set more than onesysctl for an interface, quote the wholedriver-opt field,remembering to escape the quotes for the shell if necessary. For example, if theinterface tomy-net is given nameeth0, the following example sets sysctlsnet.ipv4.conf.eth0.log_martians=1 andnet.ipv4.conf.eth0.forwarding=0, andassigns the IPv4 address192.0.2.42.

$ docker network create --subnet 192.0.2.0/24 my-net$ docker run -itd --network=name=my-net,\"driver-opt=com.docker.network.endpoint.sysctls=net.ipv4.conf.IFNAME.log_martians=1,net.ipv4.conf.IFNAME.forwarding=0\",ip=192.0.2.42 busybox
Note

Network drivers may restrict the sysctl settings that can be modified and, to protectthe operation of the network, new restrictions may be added in the future.

For more information on connecting a container to a network when using therun command,see theDocker network overview.

Mount volumes from container (--volumes-from)

$ docker run --volumes-from 777f7dc92da7 --volumes-from ba8c0c54f0f2:ro -i -t ubuntupwd

The--volumes-from flag mounts all the defined volumes from the referencedcontainers. You can specify more than one container by repetitions of the--volumes-fromargument. The container ID may be optionally suffixed with:ro or:rw tomount the volumes in read-only or read-write mode, respectively. By default,Docker mounts the volumes in the same mode (read write or read only) asthe reference container.

Labeling systems like SELinux require placing proper labels on volumecontent mounted into a container. Without a label, the security system mightprevent the processes running inside the container from using the content. Bydefault, Docker does not change the labels set by the OS.

To change the label in the container context, you can add either of two suffixes:z or:Z to the volume mount. These suffixes tell Docker to relabel fileobjects on the shared volumes. Thez option tells Docker that two containersshare the volume content. As a result, Docker labels the content with a sharedcontent label. Shared volume labels allow all containers to read/write content.TheZ option tells Docker to label the content with a private unshared label.Only the current container can use a private volume.

Detached mode (-d, --detach)

The--detach (or-d) flag starts a container as a background process thatdoesn't occupy your terminal window. By design, containers started in detachedmode exit when the root process used to run the container exits, unless youalso specify the--rm option. If you use-d with--rm, the container isremoved when it exits or when the daemon exits, whichever happens first.

Don't pass aservice x start command to a detached container. For example,this command attempts to start thenginx service.

$ docker run -d -p 80:80 my_image service nginx start

This succeeds in starting thenginx service inside the container. However, itfails the detached container paradigm in that, the root process (service nginx start) returns and the detached container stops as designed. As a result, thenginx service starts but can't be used. Instead, to start a process such asthenginx web server do the following:

$ docker run -d -p 80:80 my_image nginx -g'daemon off;'

To do input/output with a detached container use network connections or sharedvolumes. These are required because the container is no longer listening to thecommand line wheredocker run was run.

Override the detach sequence (--detach-keys)

Use the--detach-keys option to override the Docker key sequence for detach.This is useful if the Docker default sequence conflicts with key sequence youuse for other applications. There are two ways to define your own detach keysequence, as a per-container override or as a configuration property on yourentire configuration.

To override the sequence for an individual container, use the--detach-keys="<sequence>" flag with thedocker attach command. The format ofthe<sequence> is either a letter [a-Z], or thectrl- combined with any ofthe following:

  • a-z (a single lowercase alpha character )
  • @ (at sign)
  • [ (left bracket)
  • \\ (two backward slashes)
  • _ (underscore)
  • ^ (caret)

Thesea,ctrl-a,X, orctrl-\\ values are all examples of valid keysequences. To configure a different configuration default key sequence for allcontainers, seeConfiguration file section.

Add host device to container (--device)

$ docker run -it --rm\    --device=/dev/sdc:/dev/xvdc \    --device=/dev/sdd \    --device=/dev/zero:/dev/foobar \    ubuntu ls -l /dev/{xvdc,sdd,foobar}brw-rw---- 1 root disk 8, 2 Feb  9 16:05 /dev/xvdcbrw-rw---- 1 root disk 8, 3 Feb  9 16:05 /dev/sddcrw-rw-rw- 1 root root 1, 5 Feb  9 16:05 /dev/foobar

It's often necessary to directly expose devices to a container. The--deviceoption enables that. For example, adding a specific block storage device or loopdevice or audio device to an otherwise unprivileged container(without the--privileged flag) and have the application directly access it.

By default, the container is able toread,write andmknod these devices.This can be overridden using a third:rwm set of options to each--deviceflag. If the container is running in privileged mode, then Docker ignores thespecified permissions.

$ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk  /dev/xvdcCommand (m for help): q$ docker run --device=/dev/sda:/dev/xvdc:r --rm -it ubuntu fdisk  /dev/xvdcYou will not be able to write the partition table.Command (m for help): q$ docker run --device=/dev/sda:/dev/xvdc:rw --rm -it ubuntu fdisk  /dev/xvdcCommand (m for help): q$ docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk  /dev/xvdcfdisk: unable to open /dev/xvdc: Operation not permitted
Note

The--device option cannot be safely used with ephemeral devices. You shouldn'tadd block devices that may be removed to untrusted containers with--device.

For Windows, the format of the string passed to the--device option is inthe form of--device=<IdType>/<Id>. Beginning with Windows Server 2019and Windows 10 October 2018 Update, Windows only supports an IdType ofclass and the Id as adevice interface classGUID.Refer to the table defined in theWindows containerdocsfor a list of container-supported device interface class GUIDs.

If you specify this option for a process-isolated Windows container, Docker makesall devices that implement the requested device interface class GUIDavailable in the container. For example, the command below makes all COMports on the host visible in the container.

PSC:\>dockerrun--device=class/86E0D1E0-8089-11D0-9CE4-08003E301F73mcr.microsoft.com/windows/servercore:ltsc2019
Note

The--device option is only supported on process-isolated Windows containers,and produces an error if the container isolation ishyperv.

CDI devices

Container Device Interface(CDI)is a standardized mechanism for container runtimes to create containers whichare able to interact with third party devices.

CDI is currently only supported for Linux containers and is enabled by defaultsince Docker Engine 28.3.0.

With CDI, device configurations are declaratively defined using a JSON or YAMLfile. In addition to enabling the container to interact with the device node,it also lets you specify additional configuration for the device, such asenvironment variables, host mounts (such as shared objects), and executablehooks.

You can reference a CDI device with the--device flag using thefully-qualified name of the device, as shown in the following example:

$ docker run --device=vendor.com/class=device-name --rm -it ubuntu

This starts anubuntu container with access to the specified CDI device,vendor.com/class=device-name, assuming that:

  • A valid CDI specification (JSON or YAML file) for the requested device isavailable on the system running the daemon, in one of the configured CDIspecification directories.
  • The CDI feature has been enabled in the daemon; seeEnable CDIdevices.

Attach to STDIN/STDOUT/STDERR (-a, --attach)

The--attach (or-a) flag tellsdocker run to bind to the container'sSTDIN,STDOUT orSTDERR. This makes it possible to manipulate the outputand input as needed. You can specify to which of the three standard streams(STDIN,STDOUT,STDERR) you'd like to connect instead, as in:

$ docker run -a stdin -a stdout -i -t ubuntu /bin/bash

The following example pipes data into a container and prints the container's IDby attaching only to the container'sSTDIN.

$echo"test"| docker run -i -a stdin ubuntu cat -

The following example doesn't print anything to the console unless there's anerror because output is only attached to theSTDERR of the container. Thecontainer's logs still store what's written toSTDERR andSTDOUT.

$ docker run -a stderr ubuntuechotest

The following example shows a way of using--attach to pipe a file into acontainer. The command prints the container's ID after the build completes andyou can retrieve the build logs usingdocker logs. This is useful if you needto pipe a file or something else into a container and retrieve the container'sID once the container has finished running.

$ cat somefile| docker run -i -a stdin mybuilder dobuild
Note

A process running as PID 1 inside a container is treated specially byLinux: it ignores any signal with the default action. So, the processdoesn't terminate onSIGINT orSIGTERM unless it's coded to do so.

See alsothedocker cp command.

Keep STDIN open (-i, --interactive)

The--interactive (or-i) flag keeps the container'sSTDIN open, and letsyou send input to the container through standard input.

$echo hello| docker run --rm -i busybox cathello

The-i flag is most often used together with the--tty flag to bind the I/Ostreams of the container to a pseudo terminal, creating an interactive terminalsession for the container. SeeAllocate a pseudo-TTY for more examples.

$ docker run -it debianroot@10a3e71492b0:/# factor 9090: 2 3 3 5root@10a3e71492b0:/# exitexit

Using the-i flag on its own allows for composition, such as piping input tocontainers:

$ docker run --rm -i busyboxecho"foo bar baz"\  | docker run --rm -i busybox awk '{ print $2 }' \  | docker run --rm -i busybox revrab

Specify an init process

You can use the--init flag to indicate that an init process should be used asthe PID 1 in the container. Specifying an init process ensures the usualresponsibilities of an init system, such as reaping zombie processes, areperformed inside the created container.

The default init process used is the firstdocker-init executable found in thesystem path of the Docker daemon process. Thisdocker-init binary, included inthe default installation, is backed bytini.

Allocate a pseudo-TTY (-t, --tty)

The--tty (or-t) flag attaches a pseudo-TTY to the container, connectingyour terminal to the I/O streams of the container. Allocating a pseudo-TTY tothe container means that you get access to input and output feature that TTYdevices provide.

For example, the following command runs thepasswd command in adebiancontainer, to set a new password for theroot user.

$ docker run -i debian passwd rootNew password: karjalanpiirakka9Retype new password: karjalanpiirakka9passwd: password updated successfully

If you run this command with only the-i flag (which lets you send text toSTDIN of the container), thepasswd prompt displays the password in plaintext. However, if you try the same thing but also adding the-t flag, thepassword is hidden:

$ docker run -it debian passwd rootNew password:Retype new password:passwd: password updated successfully

This is becausepasswd can suppress the output of characters to the terminalusing the echo-off TTY feature.

You can use the-t flag without-i flag. This still allocates a pseudo-TTYto the container, but with no way of writing toSTDIN. The only time thismight be useful is if the output of the container requires a TTY environment.

Specify custom cgroups

Using the--cgroup-parent flag, you can pass a specific cgroup to run acontainer in. This allows you to create and manage cgroups on their own. You candefine custom resources for those cgroups and put containers under a commonparent group.

Using dynamically created devices (--device-cgroup-rule)

Docker assigns devices available to a container at creation time. Theassigned devices are added to the cgroup.allow file andcreated into the container when it runs. This poses a problem whenyou need to add a new device to running container.

One solution is to add a more permissive rule to a containerallowing it access to a wider range of devices. For example, supposingthe container needs access to a character device with major42 andany number of minor numbers (added as new devices appear), add thefollowing rule:

$ docker run -d --device-cgroup-rule='c 42:* rmw' --name my-container my-image

Then, a user could askudev to execute a script that woulddocker exec my-container mknod newDevX c 42 <minor>the required device when it is added.

Note

You still need to explicitly add initially present devices to thedocker run /docker create command.

Access an NVIDIA GPU

The--gpus flag allows you to access NVIDIA GPU resources. First you need toinstall thenvidia-container-runtime.

Note

You can also specify a GPU as a CDI device with the--device flag, seeCDI devices.

ReadSpecify a container's resourcesfor more information.

To use--gpus, specify which GPUs (or all) to use. If you provide no value, Docker uses allavailable GPUs. The example below exposes all available GPUs.

$ docker run -it --rm --gpus all ubuntu nvidia-smi

Use thedevice option to specify GPUs. The example below exposes a specificGPU.

$ docker run -it --rm --gpusdevice=GPU-3a23c669-1f69-c64e-cf85-44e9b07e7a2a ubuntu nvidia-smi

The example below exposes the first and third GPUs.

$ docker run -it --rm --gpus'"device=0,2"' ubuntu nvidia-smi

Restart policies (--restart)

Use the--restart flag to specify a container'srestart policy. A restartpolicy controls whether the Docker daemon restarts a container after exit.Docker supports the following restart policies:

FlagDescription
noDon't automatically restart the container. (Default)
on-failure[:max-retries]Restart the container if it exits due to an error, which manifests as a non-zero exit code. Optionally, limit the number of times the Docker daemon attempts to restart the container using the:max-retries option. Theon-failure policy only prompts a restart if the container exits with a failure. It doesn't restart the container if the daemon restarts.
alwaysAlways restart the container if it stops. If it's manually stopped, it's restarted only when Docker daemon restarts or the container itself is manually restarted.
unless-stoppedSimilar toalways, except that when the container is stopped (manually or otherwise), it isn't restarted even after Docker daemon restarts.
$ docker run --restart=always redis

This runs theredis container with a restart policy ofalways.If the container exits, Docker restarts it.

When a restart policy is active on a container, it shows as eitherUp orRestarting indocker ps. It can also be useful to usedocker events to see the restart policy in effect.

An increasing delay (double the previous delay, starting at 100 milliseconds)is added before each restart to prevent flooding the server. This means thedaemon waits for 100 ms, then 200 ms, 400, 800, 1600, and so on until eithertheon-failure limit, the maximum delay of 1 minute is hit, or when youdocker stop ordocker rm -f the container.

If a container is successfully restarted (the container is started and runsfor at least 10 seconds), the delay is reset to its default value of 100 ms.

Specify a limit for restart attempts

You can specify the maximum amount of times Docker attempts to restart thecontainer when using theon-failure policy. By default, Docker never stopsattempting to restart the container.

The following example runs theredis container with a restart policy ofon-failure and a maximum restart count of 10.

$ docker run --restart=on-failure:10 redis

If theredis container exits with a non-zero exit status more than 10 timesin a row, Docker stops trying to restart the container. Providing a maximumrestart limit is only valid for theon-failure policy.

Inspect container restarts

The number of (attempted) restarts for a container can be obtained using thedocker inspect command. For example, to get the number ofrestarts for container "my-container";

$ docker inspect -f"{{ .RestartCount }}" my-container2

Or, to get the last time the container was (re)started;

$ docker inspect -f"{{ .State.StartedAt }}" my-container2015-03-04T23:47:07.691840179Z

Combining--restart (restart policy) with the--rm (clean up) flag resultsin an error. On container restart, attached clients are disconnected.

Clean up (--rm)

By default, a container's file system persists even after the container exits.This makes debugging a lot easier, since you can inspect the container's finalstate and you retain all your data.

If you are running short-termforeground processes, these container filesystems can start to pile up. If you'd like Docker to automatically clean upthe container and remove the file system when the container exits, use the--rm flag:

--rm: Automatically remove the container when it exits
Note

If you set the--rm flag, Docker also removes the anonymous volumesassociated with the container when the container is removed. This is similarto runningdocker rm -v my-container. Only volumes that are specifiedwithout a name are removed. For example, when running the following command,volume/foo is removed, but not/bar:

$ docker run --rm -v /foo -v awesome:/bar busybox top

Volumes inherited via--volumes-from are removed with the same logic:if the original volume was specified with a name it isn't removed.

Add entries to container hosts file (--add-host)

You can add other hosts into a container's/etc/hosts file by using one ormore--add-host flags. This example adds a static address for a host namedmy-hostname:

$ docker run --add-host=my-hostname=8.8.8.8 --rm -it alpine/ # ping my-hostnamePING my-hostname (8.8.8.8): 56 data bytes64 bytes from 8.8.8.8: seq=0 ttl=37 time=93.052 ms64 bytes from 8.8.8.8: seq=1 ttl=37 time=92.467 ms64 bytes from 8.8.8.8: seq=2 ttl=37 time=92.252 ms^C--- my-hostname ping statistics ---4 packets transmitted, 4 packets received, 0% packet lossround-trip min/avg/max = 92.209/92.495/93.052 ms

You can wrap an IPv6 address in square brackets:

$ docker run --add-host my-hostname=[2001:db8::33] --rm -it alpine

The--add-host flag supports a specialhost-gateway value that resolves tothe internal IP address of the host. This is useful when you want containers toconnect to services running on the host machine.

It's conventional to usehost.docker.internal as the hostname referring tohost-gateway. Docker Desktop automatically resolves this hostname, seeExplore networking features.

The following example shows how the specialhost-gateway value works. Theexample runs an HTTP server that serves a file from host to container over thehost.docker.internal hostname, which resolves to the host's internal IP.

$echo"hello from host!" > ./hello$ python3 -m http.server8000Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...$ docker run\  --add-host host.docker.internal=host-gateway \  curlimages/curl -s host.docker.internal:8000/hellohello from host!

The--add-host flag also accepts a: separator, for example:

$ docker run --add-host=my-hostname:8.8.8.8 --rm -it alpine

Logging drivers (--log-driver)

The container can have a different logging driver than the Docker daemon. Usethe--log-driver=<DRIVER> with thedocker run command to configure thecontainer's logging driver.

To learn about the supported logging drivers and how to use them, refer toConfigure logging drivers.

To disable logging for a container, set the--log-driver flag tonone:

$ docker run --log-driver=none -d nginx:alpine5101d3b7fe931c27c2ba0e65fd989654d297393ad65ae238f20b97a020e7295b$ docker logs 5101d3bError response from daemon: configured logging driver does not support reading

Set ulimits in container (--ulimit)

Since settingulimit settings in a container requires extra privileges notavailable in the default container, you can set these using the--ulimit flag.Specify--ulimit with a soft and hard limit in the format<type>=<soft limit>[:<hard limit>]. For example:

$ docker run --ulimitnofile=1024:1024 --rm debian sh -c"ulimit -n"1024
Note

If you don't provide a hard limit value, Docker uses the soft limit valuefor both values. If you don't provide any values, they are inherited fromthe defaultulimits set on the daemon.

Note

Theas option is deprecated.In other words, the following script is not supported:

$ docker run -it --ulimitas=1024 fedora /bin/bash

Supported options for--ulimit:

OptionDescription
coreMaximum size of core files created (RLIMIT_CORE)
cpuCPU time limit in seconds (RLIMIT_CPU)
dataMaximum data segment size (RLIMIT_DATA)
fsizeMaximum file size (RLIMIT_FSIZE)
locksMaximum number of file locks (RLIMIT_LOCKS)
memlockMaximum locked-in-memory address space (RLIMIT_MEMLOCK)
msgqueueMaximum bytes in POSIX message queues (RLIMIT_MSGQUEUE)
niceMaximum nice priority adjustment (RLIMIT_NICE)
nofileMaximum number of open file descriptors (RLIMIT_NOFILE)
nprocMaximum number of processes available (RLIMIT_NPROC)
rssMaximum resident set size (RLIMIT_RSS)
rtprioMaximum real-time scheduling priority (RLIMIT_RTPRIO)
rttimeMaximum real-time execution time (RLIMIT_RTTIME)
sigpendingMaximum number of pending signals (RLIMIT_SIGPENDING)
stackMaximum stack size (RLIMIT_STACK)

Docker sends the values to the appropriate OSsyscall and doesn't perform any byte conversion.Take this into account when setting the values.

Fornproc usage

Be careful settingnproc with theulimit flag as Linux usesnproc to set themaximum number of processes available to a user, not to a container. For example, start fourcontainers withdaemon user:

$ docker run -d -u daemon --ulimitnproc=3 busybox top$ docker run -d -u daemon --ulimitnproc=3 busybox top$ docker run -d -u daemon --ulimitnproc=3 busybox top$ docker run -d -u daemon --ulimitnproc=3 busybox top

The 4th container fails and reports a "[8] System error: resource temporarily unavailable" error.This fails because the caller setnproc=3 resulting in the first three containers using upthe three processes quota set for thedaemon user.

Stop container with signal (--stop-signal)

The--stop-signal flag sends the system call signal to thecontainer to exit. This signal can be a signal name in the formatSIG<NAME>,for instanceSIGKILL, or an unsigned number that matches a position in thekernel's syscall table, for instance9.

The default value is defined bySTOPSIGNALin the image, orSIGTERM if the image has noSTOPSIGNAL defined.

Optional security options (--security-opt)

OptionDescription
--security-opt="label=user:USER"Set the label user for the container
--security-opt="label=role:ROLE"Set the label role for the container
--security-opt="label=type:TYPE"Set the label type for the container
--security-opt="label=level:LEVEL"Set the label level for the container
--security-opt="label=disable"Turn off label confinement for the container
--security-opt="apparmor=PROFILE"Set the apparmor profile to be applied to the container
--security-opt="no-new-privileges=true"Disable container processes from gaining new privileges
--security-opt="seccomp=unconfined"Turn off seccomp confinement for the container
--security-opt="seccomp=builtin"Use the default (built-in) seccomp profile for the container. This can be used to enable seccomp for a container running on a daemon with a custom default profile set, or with seccomp disabled ("unconfined").
--security-opt="seccomp=profile.json"White-listed syscalls seccomp Json file to be used as a seccomp filter
--security-opt="systempaths=unconfined"Turn off confinement for system paths (masked paths, read-only paths) for the container

The--security-opt flag lets you override the default labeling scheme for acontainer. Specifying the level in the following command allows you to sharethe same content between containers.

$ docker run --security-optlabel=level:s0:c100,c200 -it fedora bash
Note

Automatic translation of MLS labels isn't supported.

To disable the security labeling for a container entirely, you can uselabel=disable:

$ docker run --security-optlabel=disable -it ubuntu bash

If you want a tighter security policy on the processes within a container, youcan specify a customtype label. The following example runs a containerthat's only allowed to listen on Apache ports:

$ docker run --security-optlabel=type:svirt_apache_t -it ubuntu bash
Note

You would have to write policy defining asvirt_apache_t type.

To prevent your container processes from gaining additional privileges, you canuse the following command:

$ docker run --security-opt no-new-privileges -it ubuntu bash

This means that commands that raise privileges such assu orsudo no longer work.It also causes any seccomp filters to be applied later, after privileges have been droppedwhich may mean you can have a more restrictive set of filters.For more details, see thekernel documentation.

On Windows, you can use the--security-opt flag to specify thecredentialspec option.Thecredentialspec must be in the formatfile://spec.txt orregistry://keyname.

Stop container with timeout (--stop-timeout)

The--stop-timeout flag sets the number of seconds to wait for the containerto stop after sending the pre-defined (see--stop-signal) system call signal.If the container does not exit after the timeout elapses, it's forcibly killedwith aSIGKILL signal.

If you set--stop-timeout to-1, no timeout is applied, and the daemonwaits indefinitely for the container to exit.

The Daemon determines the default, and is 10 seconds for Linux containers,and 30 seconds for Windows containers.

Specify isolation technology for container (--isolation)

This option is useful in situations where you are running Docker containers onWindows. The--isolation=<value> option sets a container's isolation technology.On Linux, the only supported is thedefault option which uses Linux namespaces.These two commands are equivalent on Linux:

$ docker run -d busybox top$ docker run -d --isolation default busybox top

On Windows,--isolation can take one of these values:

ValueDescription
defaultUse the value specified by the Docker daemon's--exec-opt or system default (see below).
processShared-kernel namespace isolation.
hypervHyper-V hypervisor partition-based isolation.

The default isolation on Windows server operating systems isprocess, andhypervon Windows client operating systems, such as Windows 10. Process isolation has betterperformance, but requires that the image and host use the same kernel version.

On Windows server, assuming the default configuration, these commands are equivalentand result inprocess isolation:

PSC:\>dockerrun-dmicrosoft/nanoserverpowershellechoprocessPSC:\>dockerrun-d--isolationdefaultmicrosoft/nanoserverpowershellechoprocessPSC:\>dockerrun-d--isolationprocessmicrosoft/nanoserverpowershellechoprocess

If you have set the--exec-opt isolation=hyperv option on the Dockerdaemon, orare running against a Windows client-based daemon, these commands are equivalent andresult inhyperv isolation:

PSC:\>dockerrun-dmicrosoft/nanoserverpowershellechohypervPSC:\>dockerrun-d--isolationdefaultmicrosoft/nanoserverpowershellechohypervPSC:\>dockerrun-d--isolationhypervmicrosoft/nanoserverpowershellechohyperv

Specify hard limits on memory available to containers (-m, --memory)

These parameters always set an upper limit on the memory available to the container. Linux sets thison the cgroup and applications in a container can query it at/sys/fs/cgroup/memory/memory.limit_in_bytes.

On Windows, this affects containers differently depending on what type of isolation you use.

  • Withprocess isolation, Windows reports the full memory of the host system, not the limit to applications running inside the container

    PSC:\>dockerrun-it-m2GB--isolation=processmicrosoft/nanoserverpowershellGet-ComputerInfo*memory*CsTotalPhysicalMemory:17064509440CsPhyicallyInstalledMemory:16777216OsTotalVisibleMemorySize:16664560OsFreePhysicalMemory:14646720OsTotalVirtualMemorySize:19154928OsFreeVirtualMemory:17197440OsInUseVirtualMemory:1957488OsMaxProcessMemorySize:137438953344
  • Withhyperv isolation, Windows creates a utility VM that is big enough to hold the memory limit, plus the minimal OS needed to host the container. That size is reported as "Total Physical Memory."

    PSC:\>dockerrun-it-m2GB--isolation=hypervmicrosoft/nanoserverpowershellGet-ComputerInfo*memory*CsTotalPhysicalMemory:2683355136CsPhyicallyInstalledMemory:OsTotalVisibleMemorySize:2620464OsFreePhysicalMemory:2306552OsTotalVirtualMemorySize:2620464OsFreeVirtualMemory:2356692OsInUseVirtualMemory:263772OsMaxProcessMemorySize:137438953344

Configure namespaced kernel parameters (sysctls) at runtime (--sysctl)

The--sysctl sets namespaced kernel parameters (sysctls) in thecontainer. For example, to turn on IP forwarding in the containersnetwork namespace, run this command:

$ docker run --sysctl net.ipv4.ip_forward=1 someimage
Note

Not all sysctls are namespaced. Docker does not support changing sysctlsinside of a container that also modify the host system. As the kernelevolves we expect to see more sysctls become namespaced.

Currently supported sysctls

IPC Namespace:

  • kernel.msgmax,kernel.msgmnb,kernel.msgmni,kernel.sem,kernel.shmall,kernel.shmmax,kernel.shmmni,kernel.shm_rmid_forced.
  • Sysctls beginning withfs.mqueue.*
  • If you use the--ipc=host option these sysctls are not allowed.

Network Namespace:

  • Sysctls beginning withnet.*
  • If you use the--network=host option using these sysctls are not allowed.
Table of contents

[8]ページ先頭

©2009-2025 Movatter.jp