Create list and delete Docker container method summaries on Linux
- 2021-01-14 07:28:21
- OfStack
1. Start the Docker container
Start the new Docker container with the following command. This will start a new container and give you access to it using /bin /bash shell.
# docker run [OPTIONS] <IMAGE NAME> [COMMAND] [ARG...]
For example, the following command will create a new docker container with an image named "ubuntu". To list all available images, use the docker images command.
# docker run -i -t ubuntu /bin/bash
To exit the Docker container, press ctrl+p+q. This will keep the container running in the background and provide the host system console. If you use the exit command, it will stop the current container.
2. List Docker containers
After the Docker container exists, execute the following command to list all the containers that are running.
# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f2582758af13 ubuntu "/bin/bash" 2 hours ago Up 2 hours first_ubuntu
By default, the above command will only list the containers that are running. To list all containers (including stopped containers), use the following command.
# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f2582758af13 ubuntu "/bin/bash" 2 hours ago Up 2 hours first_ubuntu
6b5b5a969241 centos "/bin/bash" 2 days ago Exited (0) 24 hours ago ubuntu-web
Start/stop/connect the container
You can use the following commands to start, stop, or attach to any container. To start the container, use the following command.
# docker start <CONTAINER ID|NAME>
To stop the container, use the following command.
# docker stop <CONTAINER ID|NAME>
To attach to the currently running container, use the following command.
# docker attach <CONTAINER ID|NAME>
4. Discard the Docker container
Before deleting any containers, be sure to stop the containers. You can use the command 'docker ps-a 'to list the status of the container. If the container is still running, first stop the container using the command given in the previous steps.
Now use the following command to remove a single or multiple containers.
# docker rm <CONTAINER ID|NAME> <CONTAINER ID|NAME>
You can also use the following command to remove all stopped containers at once.
# docker rm $(docker ps -a -q)