IT/서버
Docker 명령어 정리
원창연
2020. 11. 21. 22:23
※ 팁
모든 명령어 뒤에 --help를 넣으면 옵션이 나옴
컨터에너ID에 앞 3자리만 써도 해당ID를 찾음
컨테이너ID외 NAME을 써도 됨
- CONTAINER ID : 140ab366f2db, NAMES : db2 인경우
ex) docker start 140ab366f2db
docker start 140
docker start db2
컨터에너 ID에 앞 3자리만 써도 해당ID를 찾음
ex) docker start 140ab366f2db 와 docker start 140 는 동일함
ㅁ 도커내 컨테이너의 상태확인, 실행 종료 , 삭제
▶ ps : 컨테이너의 상태
$docker ps (옵션): 실행중인 컨테이너의 목록을 확인한다
-a : 종료까지 표시
-q : 컨테이너 ID만 표시
▶ start/stop : 컨테이너의 실행 종료
$docker start 컨테이너ID
$docker stop 컨테이너ID
▶ rm : 컨테이너 삭제
$docker rm 컨테이너ID
※ 컨테이너가 종료되더라도 다시 실행하면 이전 상태가 유지된다 따라서 사용하지 않는 컨테이너는
rm 명령어를 통해 완전히 제거를 해야한다
ㅁ 컨테이너 내부 실행
▶ doker exec [옵션] conteainer command
Options:
-d, --detach Detached mode: run command in the background
--detach-keys string Override the key sequence for detaching a container
-e, --env list Set environment variables
-i, --interactive Keep STDIN open even if not attached
--privileged Give extended privileges to the command
-t, --tty Allocate a pseudo-TTY
-u, --user string Username or UID (format: <name|uid>[:<group|gid>])
-w, --workdir string Working directory inside the container
예시)
$docker exec -i -t db2 /bin/bash => db2(이미지name 및 컨테이너id)에 쉘을 실행
$docker exec -i -t db2 ls => db2(이미지name 및 컨테이너id)에 ls 명령어 실행
$docker exec db2 sh -c "cd ~ ; mkdir test ; ls"
=>sh -c 명령어를 사용하면 위에 보이는 것 처럼,연결되거나큰 따옴표로 쓰인(chained or quoted)
명령어들을 실행시킬 수 있다.
ㅁ 이미지 목록조회 및 삭제
$dokcer images : 목록조회
docker rmi 이미지명 : 삭제
docker rmi -f 이미지명 : 삭제(컨테이너 동시 삭제)
ㅁ 컨테이너 검색, 다운로드, 다운로드 설치
▶ docker search image(검색어) : 컨테이너 검색
ex) $docker search db2
- Docker Hub로부터 사용가능한 image를 찾는 명령어
- Docker는 Dokcer HUB 를 통해 Git Hub 처럼 사용자들간의 이미지 공유를 할 수 있는 환경이 구축되어 있다
- 공식이미지는 galid/centos 처럼 / 앞에 사용자의 이름이 붙지 않는 것
▶ docker pull <이미지이름 or 이미지iD> : 이미지 다운로드
$docker pull ibmcom/db2:lastest :
▶ docker run [옵션] <이미지이름 or 이미지iD> <실행할 파일> : 컨테이너 다운로드 설치 및 실행
- 단순히 image안의 파일을 실행할 목적으로 생성된 것 때문에 메인으로 실행되는 파일이 종료되면
컨테이너도 같이 종료된다 따라서 계속해서 컨테이너를 유지하고 싶다면 -d 옵션을 이용해야 한다.
- 다운받은 image를 실행한 형태인 컨테이너로 만드는 명령어이다
주요옵션
-i
--interactive=false 옵션과 동일
표준 입출력 stdin을 활성화하며 컨테이너와 연결되어있지 않더라도 표준 입력을 유지함
-t
--tty=false 옵션과 동일
TTY 모드를 사용 bash를 사용하려면 이 옵션을 설정해야 함
이 옵션을 설정하지 않으면 명령어는 입력할 수 있지만 결과가 표시되지 않음
-d
백그라운드에서 실행 즉 데몬형태
-p : 포트포워딩 HOST PORT:Docker PORT
-e : 환경변수 설정
-v : docker외부 마운트 외부:내부
-name
컨테이너 이름 설정
ex) db2 설치
docker run -itd --name db2 --privileged=true -p 50000:50000 -e LICENSE=accept -e DB2INST1_PASSWORD=db2inst1 -e DBNAME=test -v /home/dicws/DB2:/database ibmcom/db2
docker run -itd bmcom/db2:korean --name db2 --privileged=true -p 50000:50000 -e LICENSE=accept -e DB2INST1_PASSWORD=db2inst1 -e DBNAME=test -v /home/dicws/DB2:/database ibmcom/db2:korean
ex) Oracle 설치
docker run --name oracle11g -d -p 1521:1521 jaspeen/oracle-xe-11g
ex) Tomcat 설치
docker run -d --name=tomcat -p 8080:8080 tomcat:latest
부연) run 옵션
Options:
--add-host list Add a custom host-to-IP mapping (host:ip)
-a, --attach list Attach to STDIN, STDOUT or STDERR
--blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
--blkio-weight-device list Block IO weight (relative device weight) (default [])
--cap-add list Add Linux capabilities
--cap-drop list Drop Linux capabilities
--cgroup-parent string Optional parent cgroup for the container
--cidfile string Write the container ID to the file
--cpu-period int Limit CPU CFS (Completely Fair Scheduler) period
--cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota
--cpu-rt-period int Limit CPU real-time period in microseconds
--cpu-rt-runtime int Limit CPU real-time runtime in microseconds
-c, --cpu-shares int CPU shares (relative weight)
--cpus decimal Number of CPUs
--cpuset-cpus string CPUs in which to allow execution (0-3, 0,1)
--cpuset-mems string MEMs in which to allow execution (0-3, 0,1)
-d, --detach Run container in background and print container ID
--detach-keys string Override the key sequence for detaching a container
--device list Add a host device to the container
--device-cgroup-rule list Add a rule to the cgroup allowed devices list
--device-read-bps list Limit read rate (bytes per second) from a device (default [])
--device-read-iops list Limit read rate (IO per second) from a device (default [])
--device-write-bps list Limit write rate (bytes per second) to a device (default [])
--device-write-iops list Limit write rate (IO per second) to a device (default [])
--disable-content-trust Skip image verification (default true)
--dns list Set custom DNS servers
--dns-option list Set DNS options
--dns-search list Set custom DNS search domains
--entrypoint string Overwrite the default ENTRYPOINT of the image
-e, --env list Set environment variables
--env-file list Read in a file of environment variables
--expose list Expose a port or a range of ports
--group-add list Add additional groups to join
--health-cmd string Command to run to check health
--health-interval duration Time between running the check (ms|s|m|h) (default 0s)
--health-retries int Consecutive failures needed to report unhealthy
--health-start-period duration Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
--health-timeout duration Maximum time to allow one check to run (ms|s|m|h) (default 0s)
--help Print usage
-h, --hostname string Container host name
--init Run an init inside the container that forwards signals and reaps processes
-i, --interactive Keep STDIN open even if not attached
--ip string IPv4 address (e.g., 172.30.100.104)
--ip6 string IPv6 address (e.g., 2001:db8::33)
--ipc string IPC mode to use
--isolation string Container isolation technology
--kernel-memory bytes Kernel memory limit
-l, --label list Set meta data on a container
--label-file list Read in a line delimited file of labels
--link list Add link to another container
--link-local-ip list Container IPv4/IPv6 link-local addresses
--log-driver string Logging driver for the container
--log-opt list Log driver options
--mac-address string Container MAC address (e.g., 92:d0:c6:0a:29:33)
-m, --memory bytes Memory limit
--memory-reservation bytes Memory soft limit
--memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap
--memory-swappiness int Tune container memory swappiness (0 to 100) (default -1)
--mount mount Attach a filesystem mount to the container
--name string Assign a name to the container
--network string Connect a container to a network (default "default")
--network-alias list Add network-scoped alias for the container
--no-healthcheck Disable any container-specified HEALTHCHECK
--oom-kill-disable Disable OOM Killer
--oom-score-adj int Tune host's OOM preferences (-1000 to 1000)
--pid string PID namespace to use
--pids-limit int Tune container pids limit (set -1 for unlimited)
--privileged Give extended privileges to this container
-p, --publish list Publish a container's port(s) to the host
-P, --publish-all Publish all exposed ports to random ports
--read-only Mount the container's root filesystem as read only
--restart string Restart policy to apply when a container exits (default "no")
--rm Automatically remove the container when it exits
--runtime string Runtime to use for this container
--security-opt list Security Options
--shm-size bytes Size of /dev/shm
--sig-proxy Proxy received signals to the process (default true)
--stop-signal string Signal to stop a container (default "SIGTERM")
--stop-timeout int Timeout (in seconds) to stop a container
--storage-opt list Storage driver options for the container
--sysctl map Sysctl options (default map[])
--tmpfs list Mount a tmpfs directory
-t, --tty Allocate a pseudo-TTY
--ulimit ulimit Ulimit options (default [])
-u, --user string Username or UID (format: <name|uid>[:<group|gid>])
--userns string User namespace to use
--uts string UTS namespace to use
-v, --volume list Bind mount a volume
--volume-driver string Optional volume driver for the container
--volumes-from list Mount volumes from the specified container(s)
-w, --workdir string Working directory inside the container
ㅁ docker image만들기
▶ 이미지 생성
1. 반드시 "Dockerfile" 이라는 이름으로 docker file 생성
FROM "기본이미지"
ADD "이미지에 추가할 파일"
RUN "실행할 명령어"
ex) $vi Dockerfile
FROM ibmcom/db2
RUN localedef -f UTF-8 -i ko_KR ko_KR.UTF-8
ENV LANG ko_KR.UTF-8
ENV LANGUAGE ko_KR:en
ENV LC_ALL ko_KR.UTF-8
CMD ["/bin/bash"]
2. 이미지 생성
$docker build -t ibmcom/db2:korean .
-->$docker images 로 생성을 알수 있음
ㅁ pull
▶ 이미지만 가져옴
docker pull [이미지 이름]:[태그]
▶ 이미지로부터 실행
docker run -it 이미지명
ex) docker run -it ibmcom/db2:latest --name db2 --privileged=true -p 50000:50000 -e LICENSE=accept -e DB2INST1_PASSWORD=db2inst1 -e DBNAME=test -v /home/dicws/DB2:/database
ㅁ 컨테이너 환경변수 변경
1) container id 알아내기
docker inspect my_container or docker ps or docker ps -a
2) config 파일 변경
vi /var/lib/docker/containers/{container-id}/config.v2.json
해당파일은 json형식으로 되어 있으므로 수정
3) docker 컨테이너 재시작
$docker restart my_container
ㅁ 기타 명령어
docker rename [old] [new] : name변경