🐳 Docker Basic Commands – Quick Reference Notes

Published on


🐳 Docker Basic Commands – Quick Reference Notes


1. List Running Containers

docker ps

Purpose: Shows only currently running containers.
Use when: You need active container IDs or names.


2. List All Containers (Running + Stopped)

docker ps -a

Purpose: Shows all containers, including stopped ones.
Use when: You want to restart, remove, or inspect containers.


3. Kill a Container (Force Stop)

docker kill <container_name>

Purpose: Immediately terminates a running container.
Behavior: No graceful shutdown.
Use only when: Container is frozen or unresponsive.

Example:

docker kill web_server

4. Stop a Container (Graceful Stop)

docker stop <container_name>

Purpose: Safely stops a container using SIGTERM.
Preferred over: docker kill

Example:

docker stop web_server

5. Run a Container in Detached Mode

docker run -dt --name=sample <image_name>

Flags:

  • -d → Detached mode
  • -t → Terminal
  • --name → Custom container name

Example:

docker run -dt --name=myubuntu ubuntu

6. Run a Container in Interactive Mode with Bash

docker run -it --name=sample <image_name> /bin/bash

Use: Direct terminal access inside container.

Example:

docker run -it --name=testbox ubuntu /bin/bash

7. Enter an Existing Running Container

docker exec -it <container_name> /bin/bash

Purpose: Access a running container without restarting it.

Difference:

  • docker run → Creates a new container
  • docker exec → Enters existing container

Example:

docker exec -it testbox /bin/bash

8. List Docker Images

docker images

Purpose: Shows all locally available images.


9. Remove a Container

docker rm <container_name>

Rule: Container must be stopped first.

Example:

docker rm testbox

10. Remove a Docker Image

docker rmi <image_name>

Rule: No container should be using this image.

Example:

docker rmi ubuntu

11. Run a Container with Port Mapping (IMPORTANT)

docker run -dt --name=s1 -p 81:80 nginx

Meaning:

  • 81 → Host port (your machine)
  • 80 → Container port (inside container)

Use case: Access a web server from browser using:

http://localhost:81

✅ Basic Skeleton of docker run Command

docker run [OPTIONS] --name=<container_name> -p <host_port>:<container_port> <image_name> [COMMAND]

Example Skeleton in Action:

docker run -dt --name=mynginx -p 8080:80 nginx

[!CAUTION]

⚠️ Critical Rules (Non-Negotiable)

  1. You cannot remove a running container.
  2. You cannot delete an image if any container is using it.
  3. Use docker stop before docker rm.
  4. docker kill is a last resort.
  5. docker exec works only on running containers.
  6. Every docker run creates a new container

Thank you for reading. This article is part of the PaperAstro starter template.