How to run existing container docker

How to run existing container docker

How to Run Docker Containers

So, if you are new to Docker, you might wonder how to run a docker container. Let me quickly show you that.

You can create and run a container with the following command:

And then, if you want to enter the container (to run commands inside the container interactively), you can use the docker exec command:

Here’s an example where I create a new container with Ubuntu as the base image and then I enter the running Ubuntu container and run the ls command:

How to run docker container

How to run existing container docker. Смотреть фото How to run existing container docker. Смотреть картинку How to run existing container docker. Картинка про How to run existing container docker. Фото How to run existing container docker

If you want to run a docker container with a certain image and a specified command, you can do it in this fashion:

The above command will create a new container with the specified name from the specified docker image. The container name is optional.

The reason for running bash as command here is that the container won’t stop immediately.

In the above example, I didn’t name the container so it was randomly named determined_blackburn.

And as you can see, the container is running bash command in the background.

How to run existing container docker. Смотреть фото How to run existing container docker. Смотреть картинку How to run existing container docker. Картинка про How to run existing container docker. Фото How to run existing container docker

What happens if you don’t run it as a daemon (-d option) in the background?

As you can see in the example below, the container is created and I am automatically inside the container (bash shell).

The problem here is that if you exit the container, the container stops.

I had to stop the container from another terminal in the above case.

How to run existing container docker. Смотреть фото How to run existing container docker. Смотреть картинку How to run existing container docker. Картинка про How to run existing container docker. Фото How to run existing container docker

How to run an existing container

The docker run command creates a new container from the specified image. But what happens when you already have a container?

If you want to run an existing container, you must first start the container and then you can use the exec option like this:

This example will be better for your understanding:

Why use bash all the time?

In all the above examples, I have used bash or /bin/bash as the command that runs with the container. I used it because it gives a shell and when you run the container, thanks to the shell, you can run regular commands inside the container as if you are inside a regular Linux system.

You can ask the container to run any command but keep in mind that the container exists as soon as the command completes.

As you can see in the example below, there is no interactive terminal session this time. You are not ‘inside’ the container anymore because the echo command finishes almost immediately.

You can in fact run other commands as well and enter the container afterwards.

And then I use the docker exec command to get an interactive bash shell and thus enter inside the nginx container (which is basically a Linux preconfigured with nginx).

I hope you have a better understanding about how to run docker containers and why it uses certain options.

If you have questions or suggestions, do let me know in the comment section.

Docker run reference

This page details how to use the docker run command to define the container’s resources at runtime.

General form

The basic docker run command takes this form:

The docker run command must specify an IMAGE to derive the container from. An image developer can define image defaults related to:

With the docker run [OPTIONS] an operator can add to or override the image defaults set by a developer. And, additionally, operators can override nearly all the defaults set by the Docker runtime itself. The operator’s ability to override image and Docker runtime defaults is why run has more options than any other docker command.

Operator exclusive options

Only the operator (the person executing docker run ) can set the following options.

Detached vs foreground

When starting a Docker container, you must first decide if you want to run the container in the background in a “detached” mode or in the default foreground mode:

Detached (-d)

Do not pass a service x start command to a detached container. For example, this command attempts to start the nginx service.

This succeeds in starting the nginx service inside the container. However, it fails the detached container paradigm in that, the root process ( service nginx start ) returns and the detached container stops as designed. As a result, the nginx service is started but could not be used. Instead, to start a process such as the nginx web server do the following:

To do input/output with a detached container use network connections or shared volumes. These are required because the container is no longer listening to the command line where docker run was run.

To reattach to a detached container, use docker attach command.

Foreground

A process running as PID 1 inside a container is treated specially by Linux: it ignores any signal with the default action. As a result, the process will not terminate on SIGINT or SIGTERM unless it is coded to do so.

Container identification

Name (—name)

The operator can identify a container in three ways:

Identifier typeExample value
UUID long identifier“f78375b1c487e03c9438c729345e54db9d20cfa2ac1fc3494b6eb60872e74778”
UUID short identifier“f78375b1c487”
Name“evil_ptolemy”

Containers on the default bridge network must be linked to communicate by name.

PID equivalent

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

Image[:tag]

Image[@digest]

Images using the v2 or later image format have a content-addressable identifier called a digest. As long as the input used to generate the image is unchanged, the digest value is predictable and referenceable.

The following example runs a container from the alpine image with the sha256:9cacb71397b640eca97488cf08582ae4e4068513101088e9f96c9814bfda95e0 digest:

PID settings (—pid)

By default, all containers have the PID namespace enabled.

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

Example: run htop inside a container

Create this Dockerfile:

Build the Dockerfile and tag the image as myhtop :

Use the following command to run htop inside a container:

Joining another container’s pid namespace can be used for debugging that container.

Example

Start a container running a redis server:

Debug the redis container by running another container that has strace in it:

UTS settings (—uts)

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

IPC settings (—ipc)

The following values are accepted:

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: «Join another (“shareable”) container’s IPC namespace.
“host”Use the host system’s IPC namespace.

IPC (POSIX/SysV IPC) namespace provides separation of named shared memory segments, semaphores and message queues.

Shared memory segments are used to accelerate inter-process communication at memory speed, rather than through pipes or through the network stack. Shared memory is commonly used by databases and custom-built (typically C/OpenMPI, C++/using boost libraries) high performance applications for scientific computing and financial services industries. If these types of applications are broken into multiple containers, you might need to share the IPC mechanisms of the containers, using «shareable» mode for the main (i.e. “donor”) container, and «container: » for other containers.

Network settings

Publishing ports and linking to other containers only works with the default (bridge). The linking feature is a legacy feature. You should always prefer using Docker network drivers over linking.

NetworkDescription
noneNo networking in the container.
bridge (default)Connect the container to the bridge via veth interfaces.
hostUse the host’s network stack inside the container.
container:Use the network stack of another container, specified via its name or id.
NETWORKConnects the container to a user created network (using docker network create command)

Network: none

With the network is none a container will not have access to any external routes. The container will still have a loopback interface enabled in the container but it does not have any routes to external traffic.

Network: bridge

Containers can communicate via their IP addresses by default. To communicate by name, they must be linked.

Network: host

Compared to the default bridge mode, the host mode gives significantly better networking performance since it uses the host’s native networking stack whereas the bridge has to go through one level of virtualization through the docker daemon. It is recommended to run containers in this mode when their networking performance is critical, for example, a production Load Balancer or a High Performance Web Server.

—network=»host» gives the container full access to local system services such as D-bus and is therefore considered insecure.

Network: container

Example running a Redis container with Redis binding to localhost then running the redis-cli command and connecting to the Redis server over the localhost interface.

User-defined network

You can create a network using a Docker network driver or an external network driver plugin. You can connect multiple containers to the same network. Once connected to a user-defined network, the containers can communicate easily using only another container’s IP address or name.

For overlay networks or custom plugins that support multi-host connectivity, containers connected to the same multi-host network but launched from different Engines can also communicate in this way.

The following example creates a network using the built-in bridge network driver and running a container in the created network

Managing /etc/hosts

If a container is connected to the default bridge network and linked with other containers, then the container’s /etc/hosts file is updated with the linked container’s name.

Since Docker may live update the container’s /etc/hosts file, there may be situations when processes inside the container can end up reading an empty or incomplete /etc/hosts file. In most cases, retrying the read again should fix the problem.

Restart policies (—restart)

Docker supports the following restart policies:

PolicyResult
noDo not automatically restart the container when it exits. This is the default.
on-failure[:max-retries]Restart only if the container exits with a non-zero exit status. Optionally, limit the number of restart retries the Docker daemon attempts.
alwaysAlways restart the container regardless of the exit status. When you specify always, the Docker daemon will try to restart the container indefinitely. The container will also always start on daemon startup, regardless of the current state of the container.
unless-stoppedAlways restart the container regardless of the exit status, including on daemon startup, except if the container was put into a stopped state before the Docker daemon was stopped.

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

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

Examples

This will run the redis container with a restart policy of always so that if the container exits, Docker will restart it.

This will run the redis container with a restart policy of on-failure and a maximum restart count of 10. If the redis container exits with a non-zero exit status more than 10 times in a row Docker will abort trying to restart the container. Providing a maximum restart limit is only valid for the on-failure policy.

Exit Status

The exit code from docker run gives information about why the container failed to run or why it exited. When docker run exits with a non-zero code, the exit codes follow the chroot standard, see below:

125 if the error is with Docker daemon itself

126 if the contained command cannot be invoked

127 if the contained command cannot be found

Exit code of contained command otherwise

Clean up (—rm)

Security configuration

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=profile.json»White-listed syscalls seccomp Json file to be used as a seccomp filter

Automatic translation of MLS labels is not currently supported.

If you want a tighter security policy on the processes within a container, you can specify an alternate type for the container. You could run a container that is only allowed to listen on Apache ports by executing the following command:

You would have to write policy defining a svirt_apache_t type.

If you want to prevent your container processes from gaining additional privileges, you can execute the following command:

This means that commands that raise privileges such as su or sudo will no longer work. It also causes any seccomp filters to be applied later, after privileges have been dropped which may mean you can have a more restrictive set of filters. For more details, see the kernel documentation.

Specify an init process

The default init process used is the first docker-init executable found in the system path of the Docker daemon process. This docker-init binary, included in the default installation, is backed by tini.

Specify custom cgroups

Runtime constraints on resources

The operator can also adjust the performance parameters of the container:

User memory constraints

We have four ways to set user memory usage:

Always set the memory reservation value below the hard limit, otherwise the hard limit takes precedence. A reservation of 0 is the same as setting no reservation. By default (without reservation set), memory reservation is the same as the hard memory limit.

Memory reservation is a soft-limit feature and does not guarantee the limit won’t be exceeded. Instead, the feature attempts to ensure that, when memory is heavily contended for, memory is allocated based on the reservation hints/setup.

Under this configuration, when the container consumes memory more than 200M and less than 500M, the next system memory reclaim attempts to shrink container memory below 200M.

The following example set memory reservation to 1G without a hard memory limit.

The container can use as much memory as it needs. The memory reservation setting ensures the container doesn’t consume too much memory for long time, because every memory reclaim shrinks the container’s consumption to the reservation.

The following example limits the memory to 100M and disables the OOM killer for this container:

The following example, illustrates a dangerous way to use the flag:

Kernel memory constraints

Kernel memory is fundamentally different than user memory as kernel memory can’t be swapped out. The inability to swap makes it possible for the container to block system services by consuming too much kernel memory. Kernel memory includes:

You can setup kernel memory limit to constrain these kinds of memory. For example, every process consumes some stack pages. By limiting kernel memory, you can prevent new processes from being created when the kernel memory usage is too high.

Kernel memory is never completely independent of user memory. Instead, you limit kernel memory in the context of the user memory limit. Assume “U” is the user memory limit and “K” the kernel limit. There are three possible ways to set limits:

We set memory and kernel memory, so the processes in the container can use 500M memory in total, in this 500M memory, it can be 50M kernel memory tops.

We set kernel memory without -m, so the processes in the container can use as much memory as they want, but they can only use 50M kernel memory.

Swappiness constraint

For example, you can set:

CPU share constraint

By default, all containers get the same proportion of CPU cycles. This proportion can be modified by changing the container’s CPU share weighting relative to the weighting of all other running containers.

The proportion will only apply when CPU-intensive processes are running. When tasks in one container are idle, other containers can use the left-over CPU time. The actual amount of CPU time will vary depending on the number of containers running on the system.

For example, consider three containers, one has a cpu-share of 1024 and two others have a cpu-share setting of 512. When processes in all three containers attempt to use 100% of CPU, the first container would receive 50% of the total CPU time. If you add a fourth container with a cpu-share of 1024, the first container only gets 33% of the CPU. The remaining containers receive 16.5%, 16.5% and 33% of the CPU.

On a multi-core system, the shares of CPU time are distributed over all CPU cores. Even if a container is limited to less than 100% of CPU time, it can use 100% of each individual CPU core.

CPU period constraint

If there is 1 CPU, this means the container can get 50% CPU worth of run-time every 50ms.

Cpuset constraint

We can set cpus in which to allow execution for containers.

This means processes in container can be executed on cpu 1 and cpu 3.

This means processes in container can be executed on cpu 0, cpu 1 and cpu 2.

We can set mems in which to allow execution for containers. Only effective on NUMA systems.

This example restricts the processes in the container to only use memory from memory nodes 1 and 3.

This example restricts the processes in the container to only use memory from memory nodes 0, 1 and 2.

CPU quota constraint

Block IO bandwidth (Blkio) constraint

The blkio weight setting is only available for direct IO. Buffered IO is not currently supported.

If you do block IO in the two containers at the same time, by, for example:

You’ll find that the proportion of time is the same as the proportion of blkio weights of the two containers.

Additional groups

By default, the docker container process runs with the supplementary groups looked up for the specified user. If one wants to add more to that list of groups, then one can use this flag:

Runtime privilege and Linux capabilities

By default, Docker containers are “unprivileged” and cannot, for example, run a Docker daemon inside a Docker container. This is because by default a container is not allowed to access any devices, but a “privileged” container is given access to all devices (see the documentation on cgroups devices).

Capability KeyCapability Description
AUDIT_WRITEWrite records to kernel auditing log.
CHOWNMake arbitrary changes to file UIDs and GIDs (see chown(2)).
DAC_OVERRIDEBypass file read, write, and execute permission checks.
FOWNERBypass permission checks on operations that normally require the file system UID of the process to match the UID of the file.
FSETIDDon’t clear set-user-ID and set-group-ID permission bits when a file is modified.
KILLBypass permission checks for sending signals.
MKNODCreate special files using mknod(2).
NET_BIND_SERVICEBind a socket to internet domain privileged ports (port numbers less than 1024).
NET_RAWUse RAW and PACKET sockets.
SETFCAPSet file capabilities.
SETGIDMake arbitrary manipulations of process GIDs and supplementary GID list.
SETPCAPModify process capabilities.
SETUIDMake arbitrary manipulations of process UIDs.
SYS_CHROOTUse chroot(2), change root directory.

The next table shows the capabilities which are not granted by default and may be added.

Capability KeyCapability Description
AUDIT_CONTROLEnable and disable kernel auditing; change auditing filter rules; retrieve auditing status and filtering rules.
AUDIT_READAllow reading the audit log via multicast netlink socket.
BLOCK_SUSPENDAllow preventing system suspends.
BPFAllow creating BPF maps, loading BPF Type Format (BTF) data, retrieve JITed code of BPF programs, and more.
CHECKPOINT_RESTOREAllow checkpoint/restore related operations. Introduced in kernel 5.9.
DAC_READ_SEARCHBypass file read permission checks and directory read and execute permission checks.
IPC_LOCKLock memory (mlock(2), mlockall(2), mmap(2), shmctl(2)).
IPC_OWNERBypass permission checks for operations on System V IPC objects.
LEASEEstablish leases on arbitrary files (see fcntl(2)).
LINUX_IMMUTABLESet the FS_APPEND_FL and FS_IMMUTABLE_FL i-node flags.
MAC_ADMINAllow MAC configuration or state changes. Implemented for the Smack LSM.
MAC_OVERRIDEOverride Mandatory Access Control (MAC). Implemented for the Smack Linux Security Module (LSM).
NET_ADMINPerform various network-related operations.
NET_BROADCASTMake socket broadcasts, and listen to multicasts.
PERFMONAllow system performance and observability privileged operations using perf_events, i915_perf and other kernel subsystems
SYS_ADMINPerform a range of system administration operations.
SYS_BOOTUse reboot(2) and kexec_load(2), reboot and load a new kernel for later execution.
SYS_MODULELoad and unload kernel modules.
SYS_NICERaise process nice value (nice(2), setpriority(2)) and change the nice value for arbitrary processes.
SYS_PACCTUse acct(2), switch process accounting on or off.
SYS_PTRACETrace arbitrary processes using ptrace(2).
SYS_RAWIOPerform I/O port operations (iopl(2) and ioperm(2)).
SYS_RESOURCEOverride resource Limits.
SYS_TIMESet system clock (settimeofday(2), stime(2), adjtimex(2)); set real-time (hardware) clock.
SYS_TTY_CONFIGUse vhangup(2); employ various privileged ioctl(2) operations on virtual terminals.
SYSLOGPerform privileged syslog(2) operations.
WAKE_ALARMTrigger something that will wake up the system.

The default seccomp profile will adjust to the selected capabilities, in order to allow use of facilities allowed by the capabilities, so you should not have to adjust this.

Logging drivers (—log-driver)

The docker logs command is available only for the json-file and journald logging drivers. For detailed information on working with logging drivers, see Configure logging drivers.

Overriding Dockerfile image defaults

When a developer builds an image from a Dockerfile or when she commits it, the developer can set a number of default parameters that take effect when the image starts up as a container.

CMD (default command or options)

Recall the optional COMMAND in the Docker commandline:

ENTRYPOINT (default command to execute at runtime)

or two examples of how to pass more parameters to that ENTRYPOINT:

You can reset a containers entrypoint by passing an empty string, for example:

EXPOSE (incoming ports)

The following run command options work with container networking:

ENV (environment variables)

Docker automatically sets some environment variables when creating a Linux container. Docker does not set any environment variables when creating a Windows container.

The following environment variables are set for Linux containers:

VariableValue
HOMESet based on the value of USER
HOSTNAMEThe hostname associated with the container
PATHIncludes popular directories, such as /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
TERMxterm if the container is allocated a pseudo-TTY

Run your image as a container

Estimated reading time: 9 minutes

Prerequisites

Work through the steps to build a Java image in Build your Java image.

Overview

A container is a normal operating system process except that this process is isolated and has its own file system, its own networking, and its own isolated process tree separated from the host.

To run an image inside a container, we use the docker run command. The docker run command requires one parameter which is the name of the image. Let’s start our image and make sure it is running correctly. Run the following command in your terminal:

After running this command, you’ll notice that we did not return to the command prompt. This is because our application is a REST server and runs in a loop waiting for incoming requests without returning control back to the OS until we stop the container.

Let’s open a new terminal then make a GET request to the server using the curl command.

As you can see, our curl command failed because the connection to our server was refused. It means that we were not able to connect to the localhost on port 8080. This is expected because our container is running in isolation which includes networking. Let’s stop the container and restart with port 8080 published on our local network.

Start the container and expose port 8080 to port 8080 on the host.

Now, let’s rerun the curl command from above.

Success! We were able to connect to the application running inside of our container on port 8080.

Now, press ctrl-c to stop the container.

Run in detached mode

Docker started our container in the background and printed the Container ID on the terminal.

Again, let’s make sure that our container is running properly. Run the same curl command from above.

List containers

As we ran our container in the background, how do we know if our container is running, or what other containers are running on our machine? Well, we can run the docker ps command. Just like how we run the ps command in Linux to see a list of processes on our machine, we can run the docker ps command to view a list of containers running on our machine.

The docker ps command provides a bunch of information about our running containers. We can see the container ID, the image running inside the container, the command that was used to start the container, when it was created, the status, ports that exposed and the name of the container.

You are probably wondering where the name of our container is coming from. Since we didn’t provide a name for the container when we started it, Docker generated a random name. We’ll fix this in a minute, but first we need to stop the container. To stop the container, run the docker stop command which does just that, stops the container. We need to pass the name of the container or we can use the container ID.

Now, rerun the docker ps command to see a list of running containers.

Stop, start, and name containers

You should now see several containers listed. These are containers that we started and stopped, but have not been removed.

Let’s restart the container that we just stopped. Locate the name of the container we just stopped and replace the name of the container below using the restart command.

Now, list all the containers again using the docker ps command.

Notice that the container we just restarted has been started in detached mode and has port 8080 exposed. Also, observe the status of the container is “Up X seconds”. When you restart a container, it starts with the same flags or commands that it was originally started with.

Now, let’s stop and remove all of our containers and take a look at fixing the random naming issue. Find the name of your running container and replace the name in the command below with the name of the container on your system.

Now that our container is stopped, let’s remove it. When you remove a container, the process inside the container will be stopped and the metadata for the container will be removed.

To remove a container, simple run the docker rm command passing the container name. You can pass multiple container names to the command using a single command. Again, replace the container names in the following command with the container names from your system.

Now, let’s address the random naming issue. The standard practice is to name your containers for the simple reason that it is easier to identify what is running in the container and what application or service it is associated with.

That’s better! We can now easily identify our container based on the name.

Next steps

In this module, we took a look at running containers, publishing ports, and running containers in detached mode. We also took a look at managing containers by starting, stopping, and, restarting them. We also looked at naming our containers so they are more easily identifiable.

In the next module, we’ll learn how to run a database in a container and connect it to our application. See:

Feedback

Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the Docker Docs GitHub repository. Alternatively, create a PR to suggest updates.

Working with Docker Containers

How to run existing container docker. Смотреть фото How to run existing container docker. Смотреть картинку How to run existing container docker. Картинка про How to run existing container docker. Фото How to run existing container docker

How to run existing container docker. Смотреть фото How to run existing container docker. Смотреть картинку How to run existing container docker. Картинка про How to run existing container docker. Фото How to run existing container docker

Introduction

Docker is a popular containerization tool used to provide software applications with a filesystem that contains everything they need to run. Using Docker containers ensures that the software will behave the same way, regardless of where it is deployed, because its run-time environment is ruthlessly consistent.

In this tutorial, we’ll provide a brief overview of the relationship between Docker images and Docker containers. Then, we’ll take a more detailed look at how to run, start, stop, and remove containers.

Overview

We can think of a Docker image as an inert template used to create Docker containers. Images typically start with a root filesystem and add filesystem changes and their corresponding execution parameters in ordered, read-only layers. Unlike a typical Linux distribution, a Docker image normally contains only the bare essentials necessary for running the application. The images do not have state and they do not change. Rather, they form the starting point for Docker containers.

Images come to life with the docker run command, which creates a container by adding a read-write layer on top of the image. This combination of read-only layers topped with a read-write layer is known as a union file system. When a change is made to an existing file in a running container, the file is copied out of the read-only space into the read-write layer, where the changes are applied. The version in the read-write layer hides the original file but doesn’t remove it. Changes in the read-write layer exist only within an individual container instance. When a container is deleted, any changes are lost unless steps are taken to preserve them.

Working with Containers

Each time you use the docker run command, it creates a new container from the image you specify. This can be a source of confusion, so let’s take a look with some examples:

Step 1: Creating Two Containers

The command-line prompt changes to indicate we’re inside the container as the root user, followed by the 12 character container ID.

We’ll make a change by echoing some text into the container’s /tmp directory, then use cat to verify that it was successfully saved.

Now, let’s exit the container.

If we re-run the same command, an entirely new container is created:

We can tell it’s a new container because the ID in the command prompt is different, and when we look for our Example1 file, we won’t find it:

This can make it seem like the data has disappeared, but that’s not the case. We’ll exit the second container now to see that it, and our first container with the file we created, are both on the system.

When we list the containers again, both appear:

Step 2: Restarting the First Container

We find ourselves at the container’s bash prompt once again and when we cat the file we previously created, it’s still there.

We can exit the container now:

This output shows that changes made inside the container persist through stopping and starting it. It’s only when the container is removed that the content is deleted. This example also illustrates that the changes were limited to the individual container. When we started a second container, it reflected the original state of the image.

Step 3: Deleting Both Containers

We’ve created two containers, and we’ll conclude our brief tutorial by deleting them. The docker rm command, which works only on stopped containers, allows you to specify the name or the ID of one or more containers, so we can delete both with the following:

Both of the containers, and any changes we made inside them, are now gone.

Conclusion

We’ve taken a detailed look at the docker run command to see how it automatically creates a new container each time it is run. We’ve also seen how to locate a stopped container, start it, and connect to it. If you’d like to learn more about managing containers, you might be interested in the guide, Naming Docker Containers: 3 Tips for Beginners.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

docker run

Команда docker run может быть использована в комбинации с docker commit для изменения команды выполняемой контейнером. Дополнительную информацию о docker run вы можете получить в разделе cправка по команде Docker run.

Информацию о подключении контейнеров к сети, вы можете получить в разделе введение в сети Docker.

Примеры

Захват ID контейнера (—cidfile)

Эта команда создает контейнер и выводит test в консоли. Флаг cidfile указывает Docker создать новый файл и записать в него ID контейнера. Если файл уже существует, Docker вернет ошибку. Docker закроет данный файл когда docker run завершится.

Полный набор привилегий для контейнера (—privileged)

Установка рабочего каталога (-w)

Опции драйвера хранилища для контейнера

Монтирование временного файлового хранилища (—tmpfs)

Если директория монтируемая в качестве хранилища не существует, Docker автоматически создает ее. В приведенном выше примере, Docker создаст каталог /doesnt/exist перед запуском контейнера.

При монтировании docker unix сокета и statically linked docker binary (читайте установка на linux из бинарных файлов), вы даете контейнеру полный доступ к Docker демону хоста.

Команда выставляет 80 порт контейнера без открытия порта на хосте.

Метка представляет из себя пару key=value которая применяет метаданные к контейнеру. Что бы пометить контейнер двумя метками можно выполнить команду:

Формат файла меток похож на формат файла для загрузки переменных окружения. Метки не видны для процессов запущенных внутри контейнера. Следующий пример демонстрирует формат файла меток:

Подключение контейнера к сети (—network)

Вы можете подключить несколько контейнеров к одной сети. Будучи подключенными, контейнеры могут легко взаимодействовать для этого достаточно знать IP адрес контейнера или имя. Для overlay сетей или кастомных плагинов поддерживающих мульти-хост подключения, контейнеры подключенные к этой же мульти-хост сети но запущенные другим демоном также могут взаимодействовать этим способом.

Примечание: Обнаружение служб недоступно в сетях типа bridge по умолчанию. Контейнеры могут обмениваться данными по их IP-адресам по умолчанию. Для подключения по имени, они должны быть связаны между собой.

Монтирование томов из контейнера (—volumes-from)

Системы использующие метки, такие как SELinux требуют что бы соответствующие метки были размещены в содержимом томов смонтированных в контейнер. Без метки, система безопасности может блокировать процессы запущенные внутри контейнера и пытающиеся получить доступ к данным из тома. По умолчанию Docker не меняет метки установленные ОС.

Для изменения метки контекста контейнера, вы можете добавить один из двух суффиксов :z или :Z к монтируемому тому. Эти суффиксы говорят Docker переразметить объекты файлов на общих томах. Опция z указывает Docker что два контейнера разделяют содержимое тома. В результате, Docker метит контент общей меткой. Метка общего тома позволяет всем контейнерам производит чтение/запись контента. Опция Z говорит Docker пометить контент приватной меткой. Только текущий контейнер может использовать приватный том.

Подключение к STDIN/STDOUT/STDERR (-a)

Добавление устройств к контейнеру (—device)

Политики перезапуска (—restart)

ЗначениеРезультат
noНе перезапускать контейнер после завершения. Это значение по умолчанию.
on-failure[:max-retries]Перезапускает контейнер если он завершился с не нулевым статусом. Опционально можно указать количество попыток перезапуска.
alwaysВсегда перезапускает контейнер в не зависимости от статуса завершения. Когда вы выбираете данный вариант, Docker демон будет пытаться перезапустить контейнер бесконечное число раз. Также контейнер будет всегда запускаться при запуске демона, не зависимо от текущего состояния контейнера.
unless-stoppedВсегда перезапускает контейнер не зависимо от статуса завершения, но не контейнер не будет запускаться при запуске демона, если контейнер до этого был остановлен вручную.

Этот пример будет запускать контейнер redis с политикой перезапуска always, то есть если контейнер завершается, Docker перезапустит его.

Более подробную информацию по политикам перезапуска вы можете найти в разделе руководства политики перезапуска (—restart).

Добавление записей в хост файл контейнера (—add-host)

Флаги передаваемые в ip addr show зависят от того какую версию протокола вы используете в контейнерах IPv4 или IPv6. Используйте следующие флаги для получения сетевого адреса IPv4 и сетевой картой eth0 :

Установка ulimits в контейнере (—ulimit)

Использование nproc

Остановка контейнера по сигналу (—stop-signal)

Задание технологии изоляции контейнера (—isolation)

В Microsoft Windows, может принимать любое из следующих значений:

Настройка пространства имен параметров ядра (sysctls) при запуске

Примечание: Не все параметры ядра имеют пространство имен. Docker не поддерживает изменение параметров ядра внутри контейнера, который модифицирует хост-систему. По мере развития ядра мы ожидаем увидеть больше параметров ядра в пространстве имен.

Поддерживаемые параметры ядра

kernel.msgmax, kernel.msgmnb, kernel.msgmni, kernel.sem, kernel.shmall, kernel.shmmax, kernel.shmmni, kernel.shm_rmid_forced Параметры ядра начинающиеся с fs.mqueue.*

Network Namespace : Параметры ядра начинающиеся с.*

Пожалуйста, авторизуйтесь что бы оставлять комментарии.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *