Essential Docker Commands Explained: A Guide to Running, Viewing, Stopping, and Removing Containers
In the containerized development workflow, command-line interfaces (CLI) serve as the most direct bridge between developers and image repositories as well as runtime environments. Mastering common commands is not only beneficial for daily operations but also forms the foundation for building efficient, automated CI/CD pipelines. This article focuses on explaining four of the most fundamental and frequently used commands: docker run, docker ps, docker stop, and docker rm. Through practical examples, it aims to help readers deeply understand their working principles and application scenarios.docker run is the core command in the Docker ecosystem. It is not only used to start new containers but also encompasses complex operations such as creating images, mounting volumes, and setting environment variables. The essence of this command is to pull a specified image and immediately instantiate a running container. When using it, developers need to pay attention to how parameter combinations affect resource isolation and persistence.
The basic execution syntax is as follows:
docker run [OPTIONS] IMAGE [COMMAND] [ARG]
In practical development, common options include -d (run in the background), -p (port mapping), and --name (custom container name). For example, to start an Nginx server, map port 80 on the host machine to port 8080, and assign it the name "web-server", the command should be written as:
docker run -d --name web-server -p 8080:80 nginx
This command will first check if an image named nginx exists locally; if not, it will automatically pull it from the official repository. Subsequently, the container will start in the background and listen for external requests. It is worth noting that docker run creates a new container instance by default. If you need to debug or upgrade based on an existing container, it is generally not recommended to use run directly; instead, tools like docker commit or docker cp should be used in combination.
Docker Ps: Real-time Monitoring of Container Status
When the number of containers increases, manually remembering each container's ID or name becomes difficult. At this point, the docker ps command becomes an essential tool for monitoring container runtime status. By default, this command displays all running containers and lists key information such as image name, start time, status code, and port mapping situation.
By adding the -a parameter, you can view all historical container records, including those that have stopped:
docker ps -a
The output typically includes the following columns: CONTAINER ID, IMAGE, COMMAND, CREATED, STATUS, PORTS, NAMES. For example, for the previously started Nginx container, if its status changes to Exited (0), it indicates that the program has exited normally; if it displays Up 5 minutes, it means the container is currently running.
To further filter information, developers often combine the -f parameter to filter by name:
docker ps -f name=web-server
Additionally, in development environments, using --no-log-opt or pairing it with the docker logs command to view real-time log streams can make discovering error stacks inside the container more intuitive. Understanding this status information is crucial for quickly locating faults, especially in multi-node deployment scenarios where any unexpected state change could cause service interruption.
Docker Stop: Graceful Termination of Running Instances
Once a container starts, its lifecycle is controlled by the user. When it is necessary to stop a running container, the docker stop command provides a standardized interface. Unlike directly killing the process, this command allows setting a timeout, ensuring that applications inside the container have an opportunity to execute cleanup logic (such as closing database connections or releasing file locks), thereby avoiding data corruption or resource leaks.
The basic usage is:
docker stop [OPTIONS] CONTAINER [SIGTERM] [SECONDS]
By default, Docker first sends a SIGTERM signal to the main process of the container and waits up to 10 seconds; if no response is received, it forcibly terminates using the SIGKILL signal. For example, to stop the container named web-server and extend the cleanup time to 30 seconds:
docker stop web-server --time 30
This mechanism is particularly important in production environments. Assume a Web application contains an asynchronous task queue; if the process is forcibly killed directly, it may lead to lost unsubmitted orders. By reasonably configuring the --time parameter, you can give the application sufficient buffer time to complete finalization tasks. Furthermore, when stopping multiple containers in bulk, simply list all target names:
docker stop container1 container2
Docker Rm: Resource Release and Space Management
After a container finishes running, if it is not cleaned up, residual image layers and temporary files will occupy a large amount of disk space. The docker rm command is used to delete stopped container instances and is a key step in maintaining system health. This operation not only recovers memory resources but also prevents subsequent deployment errors caused by container ID conflicts.
Before execution, confirm that the container is in an Exited state:
docker ps -a | grep Exited
If there are still running processes, you must first suspend them using docker stop. The deletion command itself is simple:
docker rm container_name
For large projects, there may be hundreds of abandoned containers; in this case, wildcard batch deletion can be adopted:
docker rm $(docker ps -aq --filter status=exited)
However, use this command cautiously in production environments and always back up important data first. If a container containing critical data is accidentally deleted, you can use docker commit to save the current file system snapshot as a new image, then rebuild it to restore the data. Additionally, regularly cleaning up unused images (using docker image prune) can also significantly optimize storage space.
Comprehensive Practice Recommendations
In actual work, these four commands are often used in combination to form a complete workflow. For example, when deploying a new service, the logic loop usually follows "Start -> Monitor -> Exception Handling -> Cleanup". Developers should develop the habit of running docker rm immediately after each test to release resources; encountering runtime errors first by analyzing logs via docker logs rather than blindly restarting; and using docker ps -a to regularly audit container lifecycle status.
By proficiently mastering these basic commands, developers can manage Docker environments more efficiently, reduce risks caused by human operational errors, and lay a solid foundation for subsequent orchestration tools (such as Kubernetes).