DevOps/도커 (Docker)

[Docker] - 002. Docker CLI 와 이미지 만들기

귀찮은 개발자 2024. 4. 17. 02:43

hello world 실행

도커를 처음 시작할 때 hello-world 을 통해 온보딩을 시작할 수 있다. 

$ docker run hello-world

--- 출력 결과 ---

Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
478afc919002: Pull complete
Digest: sha256:03b30c6a3c320ff172b52bd68eddffde6ded08ce47e650fe52de861c5e9df46d
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (arm64v8)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

 

Ubuntu 실행

hello-world 을 실행했을 때 출력되는 결과를 보면  docker run -it ubuntu bash  라는 명령어를 볼 수 있다. 

터미널에 입력하는 커멘드 명령어에 보면  -it  가 있다.  -  라는 것은 실행하는 명령어에 옵션을 추가하겠다는 의미이다. 

 -it  옵션은 터미널에 대한 인터랙티브 모드를 설정하는 것을 말한다. 

인터렉티브 모드 = 대화식(Interactive) 모드

$ docker run -it ubuntu

--- 출력 결과 --- 
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
70104cd59e2a: Pull complete
Digest: sha256:1b8d8ff4777f36f19bfe73ee4df61e3a0b789caeff29caa019539ec7c9a57f95
Status: Downloaded newer image for ubuntu:latest

--- 로컬에서 컨테이너의 ubuntu 으로 쉘이 바뀌었다. (접속함) --- 
root@d7ed3c5a0fea:/#

태그 추가 및 이미지 푸시 

로컬에서 실행한 ubuntu 에 태그를 추가하고 Docker Hub 에 푸시하여 저장할 수 있다. 

개인 도커 레포지토리 서버가 있다면  my-private-docker-registry.my-domain.com/username/ubuntu:latest  라고 하면 된다. 

-- Git 과 비유하자면 git tag 이다.
$ docker tag ubuntu:latest {docker_hub의_username}/ubuntu:latest

-- Git 에 Push 하는 것처럼 Docker hub 에 있는 Repository 서버에 이미지를 저장한다.
$ docker push {docker_hub의_username}/ubuntu:latest

이미지로 도커 컨테이너 실행 

로컬에서 저장한 이미지를 사용하여 컨테이너를 실행할 수 도 있다. 또는 개인 레포지토리에서 이미지를 다운로드 받아 사용할 수 도 있다. 

$ docker run {docker_hub의_username}/ubuntu:latest

재시작, 스팩보기, 옵션 추가하기 

 restart  는 컨테이너를 재시작 할 수 있다. (즉 재부팅이다.)

 inspect  는 컨테이너의 상세 정보를 확인할 수 있다. (내 컴퓨터의 디스크, 인터넷, 램, CPU 등을 확인 가능)

 run  은 컨테이너를 실행하겠다는 의미이며  -d  옵션은 백드라운드에서 실행하겠다는 의미이다. 

$ docker restart {container_id} 또는 {container_name}
$ docker inspect {container_id} 또는 {container_name}
$ docker run -d {docker_hub의_username}/ubuntu:latest

자주쓰는 명렁어

 docker help  을 사용하면 Docker 에서 지원하는 명령어를 볼 수 있다.

자주 쓰는 매지니먼트 명령어로는 compose, container, image, network, trush 가 있으며 일반 커멘드는 build, cp, inspect, images, logs, ps, pull, push, restart, rm, rmi, run, start 정도가 있다. 

 

만약  docker cp  에 대해 궁금하다면   --help  플래그를 추가하여 아래와 같이 확인할 수 있다. 

docker cp --help                 

Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
        docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

Copy files/folders between a container and the local filesystem

Use '-' as the source to read a tar archive from stdin
and extract it to a directory destination in a container.
Use '-' as the destination to stream a tar archive of a
container source to stdout.

Options:
  -a, --archive       Archive mode (copy all uid/gid information)
  -L, --follow-link   Always follow symbol link in SRC_PATH

 

적극적으로 도커 개발환경에서 개발을 하다 보면 이러한 명령어들은 금방 익숙해진다.

$ docker help
--- 출력 결과 --- 
Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/Users/kyungseo-park/.docker")
  -c, --context string     Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default "/Users/kyungseo-park/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/Users/kyungseo-park/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/Users/kyungseo-park/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  builder     Manage builds
  buildx*     Docker Buildx (Docker Inc., v0.10.0)
  compose*    Docker Compose (Docker Inc., v2.15.1)
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  dev*        Docker Dev Environments (Docker Inc., v0.0.5)
  extension*  Manages Docker extensions (Docker Inc., v0.2.17)
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  sbom*       View the packaged-based Software Bill Of Materials (SBOM) for an image (Anchore Inc., 0.6.0)
  scan*       Docker Scan (Docker Inc., v0.23.0)
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes

Run 'docker COMMAND --help' for more information on a command.

To get more help with docker, check out our guides at https://docs.docker.com/go/guides/