This is an old revision of the document!
Table of Contents
Docker - Containers - Run a Docker Container
Launching a container is simple as docker run + the image name you would like to run + the command to run within the container.
If the image doesn't exist on your local machine, Docker will attempt to fetch it from the public image registry.
Containers can be run in different modes:
- Attached mode: The default mode. The container is attached to the terminal session and output of the process will be displayed on your terminal.
- Detached mode: Runs the process in the background, and keeps the container running after exiting from the terminal session.
- Interactive mode: Allows you to execute commands inside the container that is still running.
Run a Container in Attached Mode
docker container run nginx
NOTE: You can press CTRL + C to stop the running Nginx container.
Run a Container Under a Specific Name
docker container run --name docker-nginx nginx
where:
- docker-nginx is the name of the container.
- nginx is the name of the Docker image that Docker will download from the Docker Hub registry.
Run a Container in Detached Mode
Runs the container in the background.
docker container run --name docker-nginx -d nginx
Verify the running container:
docker ps
returns:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 0bb07d011cc9 nginx "/docker-entrypoint.…" 7 minutes ago Up 7 minutes 80/tcp docker-nginx
Run a Container in Interactive Mode
docker container run --name docker-nginx -it nginx /bin/bash
Run a Container and Publish Container Ports
docker container run --name docker-nginx -d -p 8080:80 nginx
where:
- 8080 is the port of the Docker host.
- 80 is the port of the container where the application is running.
NOTE: You can verify the port 8080 using the URL http://docker-host-ip:8080 in your web browser.
An optional host-ip can also be set:
docker container run -p [host-ip]:[host-port]:[container-port]
Example
For example, if you ran /bin/echo hello world as your command, the container will start, print hello world and then stop:
docker run ubuntu /bin/echo hello world
NOTE: Docker containers stop running as soon as the command they issued is complete, so this example will stop the container when the echo command has displayed “hello world”.
An alternative method is:
docker run -ti ubuntu
- -t: Runs a terminal.
- -i: Allow us to interact with it.
This allows continuous use of the container until the terminal is exited by running the exit command.