Microsoft MVP성태의 닷넷 이야기
Linux: 61. docker - 원격 제어를 위한 TCP 바인딩 추가 [링크 복사], [링크+제목 복사]
조회: 3707
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

docker - 원격 제어를 위한 TCP 바인딩 추가

예전에, Portainer 등의 서비스에서 관리를 하기 위해, 혹은 docker 클라이언트 측의 -H 옵션으로 접근하기 위해 daemon.json 파일의 "hosts" 옵션을 추가하는 방법을 알아봤는데요,

Portainer에 윈도우 컨테이너를 등록하는 방법
; https://www.sysnet.pe.kr/2/0/12289

리눅스의 경우에도 daemon.json 파일의 설정을 바꿔야 하는 것은 동일하지만 접근 방법이 다소 다릅니다.

$ cat /etc/docker/daemon.json
{
  "insecure-registries" : ["192.168.100.51:5000"]
}

윈도우와는 달리 기본 IPC 통신 방법이 npipe가 아닌 리눅스 소켓이기 때문에,

$ netstat -ano | grep docker
unix  2      [ ACC ]     STREAM     LISTENING     45095    /var/run/docker.sock
unix  2      [ ACC ]     STREAM     LISTENING     228938836 /var/run/docker/metrics.sock
unix  2      [ ACC ]     STREAM     LISTENING     228931446 /var/run/docker/libnetwork/a3ed856b16e8.sock

daemon.json 파일의 내용을 다음과 같이 변경해야 합니다.

$ cat /etc/docker/daemon.json
{
  "insecure-registries" : ["192.168.100.51:5000"],
  "hosts": ["tcp://0.0.0.0:2375", "unix:///var/run/docker.sock"]
}

$ dockerd --validate --config-file=/etc/docker/daemon.json
configuration OK

그런 후, service의 설정 파일에서 ExecStart 실행 옵션을 조정해야 하는데요, 우선 기존 ExecStart의 옵션을 알아내기 위해 docker.service 위치를 알아내고,

$ sudo systemctl status docker.service
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2023-06-26 16:31:48 KST; 59s ago
     Docs: https://docs.docker.com
...[생략]...

ExecStart 명령행을 확인합니다.

$ cat /usr/lib/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target docker.socket firewalld.service containerd.service time-set.target
Wants=network-online.target containerd.service
Requires=docker.socket

[Service]
Type=notify
# the default is not to use systemd for cgroups because the delegate issues still
# exists and systemd currently does not support the cgroup feature set required
# for containers run by docker
ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutStartSec=0

...[생략]...

위의 명령행에서 "fd://"를 제거한 ExecStart를 설정해야 하는데요, 이 값을 직접 "/usr/lib/systemd/system/docker.service" 파일에서 편집하기보다는 다음과 같이 새롭게 override.conf 파일을 생성해 재정의하는 방식으로 진행해 보겠습니다.

$ mkdir -p /etc/systemd/system/docker.service.d

$ cd /etc/systemd/system/docker.service.d

// 이 디렉터리에 override.conf 파일을 생성 후, 다음의 내용을 갖도록 편집

$ cat override.conf
[Service]
ExecStart=
ExecStart=/usr/bin/dockerd --containerd=/run/containerd/containerd.sock

이후 서비스를 재시작하면,

$ sudo systemctl daemon-reload

$ sudo systemctl restart docker.service

/etc/systemd/system/docker.service.d/override.conf 파일에 설정한 값이 반영된 것을 확인할 수 있고,

$ sudo systemctl status docker.service
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; enabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/docker.service.d
           └─override.conf
   Active: active (running) since Mon 2023-06-26 16:40:01 KST; 4s ago
     Docs: https://docs.docker.com
 Main PID: 13173 (dockerd)
    Tasks: 122
   Memory: 57.2M
   CGroup: /system.slice/docker.service
           ├─13173 /usr/bin/dockerd --containerd=/run/containerd/containerd.sock
...[생략]...
...[생략]... level=info msg="[graphdriver] using prior storage driver: overlay2"
...[생략]... level=info msg="Loading containers: start."
...[생략]... level=info msg="Default bridge (docker0) is assigned with an IP address 172.17.0.0/16. Daemon optio...d IP address"
...[생략]... level=info msg="Loading containers: done."
...[생략]... level=warning msg="WARNING: API is accessible on http://0.0.0.0:2375 without encryption.\n         Access to the...
...[생략]... level=info msg="Docker daemon" commit=659604f graphdriver=overlay2 version=24.0.2
...[생략]... level=info msg="Daemon has completed initialization"
...[생략]... level=info msg="API listen on /var/run/docker.sock"
...[생략]... systemd[1]: Started Docker Application Container Engine.
...[생략]... dockerd[23914]: time="...[생략]..." level=info msg="API listen on [::]:2375"

명령행에 "-H fd://" 옵션이 삭제되었으므로 해당 옵션을 이제 daemon.json 파일에 있는 것으로 적용하게 돼 위와 같이 메시지에 나오는 것처럼 2375 포트를 대기하는 TCP 소켓을 확인할 수 있습니다.

$ netstat -tano | grep 2375
tcp6       0      0 :::2375                 :::*                    LISTEN      off (0.00/0/0)

"tcp6"이라고 나오기는 하지만 IPv4에 해당하는 "tcp"도 포함하고 있다고 하므로 사용에 문제가 없습니다.




위와 같이 설정했으면 이제 다른 컴퓨터에서 docker -H 명령을 내려 원격 제어가 가능합니다.

// docker host 컴퓨터의 IP가 192.168.100.50이라고 가정하고,
// 다른 컴퓨터에서 IPv4로 접속

$ docker -H 192.168.100.50:2375 info
...[생략]...

만약 로컬에서는 되는데,

$ docker -H 127.0.0.1:2375 info

원격에서만 안 된다면 방화벽을 조사해야 합니다.

Linux - 외부에서의 접속을 허용하기 위한 TCP 포트 여는 방법
; https://www.sysnet.pe.kr/2/0/13385




마지막으로, ExecStart의 값에서 "-H fd://"를 제거하지 않고 daemon.json에 "hosts"를 포함하게 되면, docker.service 시작에 실패하게 됩니다.

...[생략]... dockerd[29113]: unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives are specified both as a flag and in the configuration file: hosts: (from flag: [fd://], from file: [tcp://0.0.0.0:2375 unix:///var/run/docker.sock])
...[생략]...  systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE
...[생략]...  systemd[1]: Failed to start Docker Application Container Engine.
-- Subject: Unit docker.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
-- 
-- Unit docker.service has failed.
-- 
-- The result is failed.

즉, "fd://" 옵션의 사용은 배타적으로 설정해야 합니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/28/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13432정성태10/31/20232453오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232789스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232677닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232960닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233035닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233249닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233408스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233195닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233173스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233318닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233395닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235583스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233219스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233924닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233454닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233258오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233756닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233514디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233709닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236991닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233492Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20235030닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233887닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233843Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233588닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233557VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...