화. 8월 12th, 2025

G: Welcome, future Docker enthusiast! 👋 Have you ever found yourself tangled in the complexities of setting up consistent development environments, or struggled with “it works on my machine!” issues? Enter Docker! 🐳 It’s a game-changer for developers and operations teams alike, offering a lightweight, portable, and self-sufficient way to package applications and their dependencies.

This comprehensive guide will demystify the core Docker commands, focusing on the three pillars: Images, Containers, and Networks. We’ll also touch upon Volumes, which are crucial for data persistence. By the end, you’ll have a solid foundation to confidently navigate the Docker ecosystem. Let’s dive in! 🚀


1. Docker Images: The Blueprints of Your Applications 🏗️

Think of a Docker image as a static, immutable blueprint or a template. It’s a lightweight, standalone, executable package that includes everything needed to run a piece of software, including the code, a runtime, libraries, environment variables, and config files.

Key Image Commands:

  • docker pull [IMAGE_NAME]:[TAG]: Downloads an image from Docker Hub (the default registry) or a private registry. If no tag is specified, it defaults to latest.

    • Example 1: Pulling the latest Nginx web server image.
      docker pull nginx:latest
      Using default tag: latest
      latest: Pulling from library/nginx
      ... (download progress) ...
      Digest: sha256:...
      Status: Downloaded newer image for nginx:latest
      docker.io/library/nginx:latest
    • Example 2: Pulling a specific version of Ubuntu.
      docker pull ubuntu:22.04
  • docker images or docker image ls: Lists all images stored on your local machine.

    • Example:
      docker images
      REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
      nginx         latest    53d650123533   2 days ago      187MB
      ubuntu        22.04     2b740e700764   2 weeks ago     77.9MB
      hello-world   latest    d2c94c258dcb   2 months ago    13.3kB

      💡 Tip: IMAGE ID is a unique identifier. TAG helps distinguish different versions of the same image.

  • docker build -t [IMAGE_NAME]:[TAG] [PATH_TO_DOCKERFILE]: Builds a new image from a Dockerfile. A Dockerfile is a text file containing instructions for creating a Docker image.

    • Example: Let’s say you have a Dockerfile in your current directory (.).
      # Dockerfile example
      FROM node:18-alpine
      WORKDIR /app
      COPY package*.json ./
      RUN npm install
      COPY . .
      EXPOSE 3000
      CMD ["npm", "start"]
      docker build -t my-nodejs-app:1.0 .
      [+] Building 5.3s (10/10) FINISHED
      ... (build output) ...
      Successfully built d9b6b9d6e8f0
      Successfully tagged my-nodejs-app:1.0

      This command reads the Dockerfile and creates a new image named my-nodejs-app with tag 1.0.

  • docker rmi [IMAGE_NAME]:[TAG] or docker rmi [IMAGE_ID]: Removes one or more images. You cannot remove an image if a container is currently using it.

    • Example 1: Removing the Ubuntu 22.04 image.
      docker rmi ubuntu:22.04
    • Example 2: Force removal (if no running containers use it, but might be associated with stopped ones).
      docker rmi -f old-image:1.0
    • Example 3: Removing all dangling (untagged) images to free up space.
      docker image prune

      This is a great way to clean up! ✅


2. Docker Containers: The Running Instances of Your Apps 🚀

A Docker container is a runnable instance of an image. You can create, start, stop, move, or delete a container. Each container is an isolated environment, meaning multiple containers can run on the same host without interfering with each other.

Key Container Commands:

  • docker run [OPTIONS] [IMAGE_NAME]:[TAG] [COMMAND]: Creates and starts a new container from an image. This is one of the most frequently used commands!

    • Common Options:
      • -d (detached mode): Runs the container in the background.
      • -p [HOST_PORT]:[CONTAINER_PORT] (port mapping): Maps a port on your host machine to a port inside the container.
      • -v [HOST_PATH]:[CONTAINER_PATH] (volume mount): Mounts a host directory or a named volume into the container for data persistence.
      • --name [CONTAINER_NAME] (name): Assigns a custom name to your container, making it easier to reference.
      • --rm (remove on exit): Automatically removes the container when it exits. Great for temporary containers!
      • -it (interactive TTY): Keeps STDIN open and allocates a pseudo-TTY, useful for interactive sessions (e.g., shell into a container).
      • --network [NETWORK_NAME] (network): Connects the container to a specific network.
    • Example 1: Run Nginx in detached mode, mapping host port 8080 to container port 80, and give it a name.
      docker run -d -p 8080:80 --name my-nginx-web nginx:latest

      Now you can access Nginx at http://localhost:8080 in your browser! 🌐

    • Example 2: Run an Ubuntu container interactively to explore its file system.
      docker run -it --rm ubuntu:22.04 bash

      You’ll get a bash shell prompt inside the Ubuntu container. Type exit to leave.

  • docker ps or docker container ls: Lists running containers. Add -a to show all containers (running and stopped).

    • Example:
      docker ps
      CONTAINER ID   IMAGE         COMMAND                  CREATED         STATUS         PORTS                  NAMES
      c9f1a2b3c4d5   nginx:latest  "/docker-entrypoint.s"   5 minutes ago   Up 5 minutes   0.0.0.0:8080->80/tcp   my-nginx-web

      STATUS tells you if it’s up, exited, etc. PORTS shows the mappings.

  • docker stop [CONTAINER_NAME_OR_ID]: Stops one or more running containers gracefully.

    • Example:
      docker stop my-nginx-web
  • docker start [CONTAINER_NAME_OR_ID]: Starts one or more stopped containers.

    • Example:
      docker start my-nginx-web
  • docker restart [CONTAINER_NAME_OR_ID]: Restarts one or more containers.

    • Example:
      docker restart my-nginx-web
  • docker rm [CONTAINER_NAME_OR_ID]: Removes one or more stopped containers. Use -f to force removal of running containers (not recommended unless necessary).

    • Example 1: Removing a stopped container.
      docker rm my-nginx-web
    • Example 2: Removing all stopped containers (a useful cleanup trick).
      docker rm $(docker ps -aq)

      ⚠️ Be careful with this one! It removes all stopped containers.

  • docker exec -it [CONTAINER_NAME_OR_ID] [COMMAND]: Executes a command inside a running container. Essential for debugging or administrative tasks.

    • Example: Get a bash shell inside your running Nginx container.
      docker exec -it my-nginx-web bash

      Now you can run commands like ls -l /etc/nginx to inspect the Nginx configuration.

  • docker logs [CONTAINER_NAME_OR_ID]: Fetches the logs of a container. Add -f to follow logs in real-time.

    • Example: View Nginx access logs.
      docker logs -f my-nginx-web

3. Docker Networks: Enabling Container Communication 🌐

By default, Docker containers can communicate with each other on the same host using a “bridge” network. However, creating custom networks offers better isolation, name resolution (containers can refer to each other by name), and organization.

Key Network Commands:

  • docker network ls: Lists all Docker networks on your system.

    • Example:
      docker network ls
      NETWORK ID     NAME      DRIVER    SCOPE
      3d1a2b3c4d5e   bridge    bridge    local
      6f7g8h9i0j1k   host      host      local
      l2m3n4o5p6q7   none      null      local

      bridge is the default. host means the container shares the host’s network stack. none means no network connectivity.

  • docker network create [NETWORK_NAME]: Creates a new custom bridge network.

    • Example: Create a network for your web application.
      docker network create my-app-network
  • docker network inspect [NETWORK_NAME_OR_ID]: Displays detailed information about a network, including connected containers.

    • Example:
      docker network inspect my-app-network

      This will show you JSON output with configuration, connected containers, and their IP addresses within that network.

  • docker run ... --network [NETWORK_NAME]: Connect a container to a specific network during creation.

    • Example: Running a database and a web app on the same custom network.

      # Run a PostgreSQL database on 'my-app-network'
      docker run -d --name my-postgres --network my-app-network \
          -e POSTGRES_DB=mydb \
          -e POSTGRES_USER=user \
          -e POSTGRES_PASSWORD=password \
          postgres:14
      
      # Run your Node.js app, connecting to the database using its container name
      docker run -d -p 3000:3000 --name my-web-app --network my-app-network \
          my-nodejs-app:1.0

      Now, my-web-app can reach my-postgres using the hostname my-postgres (no IP address needed!), thanks to Docker’s built-in DNS resolution on custom networks. This is powerful! ✨

  • docker network connect [NETWORK_NAME] [CONTAINER_NAME_OR_ID]: Connects a running container to an existing network.

    • Example:
      docker network connect my-app-network my-existing-container
  • docker network disconnect [NETWORK_NAME] [CONTAINER_NAME_OR_ID]: Disconnects a container from a network.

    • Example:
      docker network disconnect bridge my-nginx-web
  • docker network rm [NETWORK_NAME_OR_ID]: Removes one or more custom networks.

    • Example:
      docker network rm my-app-network

4. Docker Volumes: Persisting Your Data 💾

Containers are ephemeral by nature – if you remove a container, any data written inside it is lost. Docker volumes provide a way to store data generated by Docker containers persistently and independently of the container’s lifecycle.

Types of Volumes:

  • Named Volumes: Docker manages the storage location on the host. This is the recommended approach for most Docker data persistence.
  • Bind Mounts: You directly control the exact mount point on the host file system. Useful for development (e.g., mounting source code).

Key Volume Commands (Focusing on Named Volumes):

  • docker volume create [VOLUME_NAME]: Creates a new named volume.

    • Example:
      docker volume create my-database-data
  • docker volume ls: Lists all Docker volumes.

    • Example:
      docker volume ls
      DRIVER    VOLUME NAME
      local     my-database-data
  • docker volume inspect [VOLUME_NAME]: Displays detailed information about a volume, including its host path.

    • Example:
      docker volume inspect my-database-data
  • docker run -v [VOLUME_NAME]:[CONTAINER_PATH] ...: Mounts a named volume to a container.

    • Example: Run a PostgreSQL container with a persistent volume for its data.
      docker run -d --name my-persistent-postgres --network my-app-network \
          -v my-database-data:/var/lib/postgresql/data \
          -e POSTGRES_DB=mydb \
          -e POSTGRES_USER=user \
          -e POSTGRES_PASSWORD=password \
          postgres:14

      Even if you stop and remove my-persistent-postgres, my-database-data will retain your database files! When you run a new PostgreSQL container using the same volume, your data will still be there. Super important for stateful applications! ✅

  • docker volume rm [VOLUME_NAME]: Removes one or more volumes.

    • Example:
      docker volume rm my-database-data

      ⚠️ Be careful! This deletes the data permanently.


5. Beyond the Basics: Essential Tips & Tricks ✨

Now that you’ve got the core commands down, here are a few more to boost your Docker workflow:

  • docker system prune: Cleans up unused Docker objects (stopped containers, unused networks, dangling images, build cache). This is your best friend for freeing up disk space!

    • Example:
      docker system prune -a

      The -a flag means “all unused data,” including images not associated with any container. Use with caution, but regularly for development environments.

  • docker stats: Displays a live stream of resource usage statistics for running containers (CPU, memory, network I/O).

    • Example:
      docker stats
      CONTAINER ID   NAME             CPU %     MEM USAGE / LIMIT     MEM %     NET I/O           BLOCK I/O         PIDS
      c9f1a2b3c4d5   my-nginx-web     0.00%     4.639MiB / 7.785GiB   0.06%     546B / 0B         0B / 0B           7
  • docker-compose: While not a single Docker command, docker-compose is an invaluable tool for defining and running multi-container Docker applications. It uses a YAML file (docker-compose.yml) to configure your application’s services, networks, and volumes in one place.

    • Example docker-compose.yml snippet:
      version: '3.8'
      services:
        web:
          build: .
          ports:
            - "3000:3000"
          volumes:
            - .:/app
          depends_on:
            - db
        db:
          image: postgres:14
          environment:
            POSTGRES_DB: mydb
            POSTGRES_USER: user
            POSTGRES_PASSWORD: password
          volumes:
            - my-database-data:/var/lib/postgresql/data
      volumes:
        my-database-data:
    • Running it:
      docker-compose up -d

      This single command builds, creates, starts, and links your web app and database! Mind-blowing efficiency! 🤯


Conclusion: Your Docker Journey Has Just Begun! 🏁

Congratulations! You’ve just taken a deep dive into the most essential Docker commands for managing images, containers, networks, and volumes. These commands are the building blocks of almost any Dockerized application.

Docker is a powerful tool that brings consistency, scalability, and efficiency to your development and deployment workflows. The best way to solidify your understanding is to practice, practice, practice!

  • Try running different images.
  • Experiment with port mappings and volume mounts.
  • Build your own Dockerfile for a simple application.
  • Set up a multi-service application using a custom network.

As you become more comfortable, explore advanced topics like docker-compose (a must for real-world apps!), Docker Swarm, Kubernetes, and continuous integration with Docker.

Happy Dockering! May your containers always run smoothly. ✨

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다