본문 바로가기
🧑🏻‍💻 Develop/Docker

Docker Detach vs Attach mode (Background vs Foreground)

by dev-jaesoon 2023. 5. 8.

Docker 를 실행 시에는 모드를 설정하는 옵션이 2가지 있다.

  • Detach Mode (Background 실행)
    • docker command : start
    • docker option : --detach / -d
    • docker-compose options : -d
  • Attach Mode (Foreground 실행)
    • docker command : run
    • docker option : --attach / -a
    • docker-compose options : 없음

Background vs Foreground
참고자료 : https://www.baeldung.com/linux/foreground-background-process
A process that connects to the terminal is called a foreground job. A job is said to be in the foreground because it can communicate with the user via the screen and the keyboard.

On the other hand, a process that disconnects from the terminal and cannot communicate with the user is called a background job. If the background job requires interaction with the user, it will stop and wait until establishing a connection to the terminal.

We can place the jobs that do not require interaction from the user as they run (like sorting a large file) in the background. This allows the user to access the terminal and continue to work, instead of waiting for a long job to finish:

Detach Mode (container background)

  • Docker 를 Service 형태로 실행할 때 사용되는 방식으로 terminal 을 종료해도 지속적으로 process 의 실행이 유지된다.
  • container 내에서 program 이 foreground 로 실행 되어 있어야 하고, 그렇지 않으면 container 는 자동으로 종료된다.
    • 예를 들어 ubuntu image 를 -d 옵션으로 실행할 경우 바로 종료됨
    • 별도의 Server application 등을 foreground 로 실행해야 함

How to run

  • 생성된 container 를 docker start command 로 실행할 경우 background 에서 실행된다.
  • container 생성 시 사용하는 docker run command 에 -d 옵션을 붙임으로써 background 에서 실행되게 할 수 있다.

Container log

  • log 옵션을 사용하여 출력되는 log 를 확인 가능하다
      $ docker log {container_id or container_name}
  • 하지만, 기본적으로 Standard stream 이 활성화되지 않은 상태로 container 를 실행하기 때문에, user input 이 불가능하다.

Access to container

  • 이미 Detach Mode 로 실행되어 있는 container 의 경우, -it 옵션을 통해 Standard stream 을 활성화하여 사용할 수 있다.
    $ docker exec -it {container_id or container_name} /bin/bash 
  • 혹은 실행 시, -a 옵션을 사용하면 Foreground 로 실행되기 때문에, terminal 을 통한 Standard stream 이 사용 가능하다.

Attach Mode (container foreground)

  • 현재 실행 중인 terminal 에 container 의 동작 상태를 출력하는 방식으로, container 의 동작을 보기 쉽기 때문에 test, debug 시에 사용된다.
  • terminal 과 process 가 부모 - 자식으로 연결되기 때문에, terminal 의 연결이 종료되면 container 도 종료되게 된다.
  • foreground 로 실행하면서 실행 상태를 유지하고 싶다면, tmux 등으로 따로 terminal process 를 관리할 필요가 있다.
  • docker-compose 도 기본적으로 attach mode 로 실행된다.

'🧑🏻‍💻 Develop > Docker' 카테고리의 다른 글

Docker RUN vs ENTRYPOINT vs CMD  (0) 2023.05.09

댓글0