Shell Script 문법 정리
Title: Bash Shell Script 문법 정리 Author: DongDongE Tags: Programming Release: 2021.02.08 [Shell
Docker Container 생성은 아래 명령을 통해 이미지를 기반으로 컨테이너를 생성할 수 있다.
컨테이너 생성은 단순히 생성만 하므로, 생성후 시작은 하지 않습니다.
docker create <옵션> 이미지명 <명령어> <인자>
또는docker container create <옵션> 이미지명 <명령어> <인자>
dongdonge@dongdonge$ sudo docker create --help
Usage: docker create [OPTIONS] IMAGE [COMMAND] [ARG...]
Create a new container
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)
--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
--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
dongdonge@dongdonge$ sudo docker create --name "dongdonge" ubuntu
0e5851f85ecd9f3a75a8901690b7f8eb298240334d43ef4d99ad15dca81cd2a2
--name 옵션을 통해 도커 컨테이너 생성이 이름을 지정할 수 있으며, 아래 명령어를 통해 생성된 도커 컨테이너를 확인할 수 있습니다.
dongdonge@dongdonge$ sudo docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0e5851f85ecd ubuntu "/bin/bash" 5 seconds ago Created dongdonge
위 명령어를 통해 Ubuntu 도커 이미지를 기반으로 컨테이너를 생성할 수 있습니당.
--help 옵션을 통해 구체적은 옵션 정보를 확인할 수 있으므로, 생성이 속성에 맞게 생성하시면 됩니당.
Docker run 명령어를 통해 이미지를 기반으로 컨테이너 생성후 바로 시작을 할 수 있습니다.
docker run <옵션> 이미지명 <명령어> <인자>
또는docker container run <옵션> 이미지명 <명령어> <인자>
run 옵션은 몇개만 한글로 적어두고, 나머지는 영문으로 그대로 두겠습니당.
dongdonge@dongdonge$ sudo docker run --help
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Run a command in a new container
Options:
--add-host list 사용자 지정 호스트와 IP 매핑 추가 (host:ip)
-a, --attach list STDIN(표준입력), STDOUT(표준출력), 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 리눅스 기능 추가
--cap-drop list 리눅스 기능 삭제
--cgroup-parent string Optional parent cgroup for the container
--cidfile string 파일에 컨테이너 ID 출력
--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 컨테이너를 백그라운드로 실행하고 컨테이너 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 사용자 지정 DNS 서버 설정
--dns-option list 사용자 지정 DNS 옵션 설정
--dns-search list 사용자 지정 DNS 검색 도메인 설정
--entrypoint string Overwrite the default ENTRYPOINT of the image
-e, --env list 환경 변수 지정
--env-file list 파일에서 환경변수 리스트 불러 오기
--expose list 포트 또는 포트 범위 리스트
--group-add list 그룹에 추가
--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 컨테이너 호스트 이름
--init Run an init inside the container that forwards signals and reaps
processes
-i, --interactive 컨테이너를 STDIN(표준입력)으로 열어서 상태 유지
--ip string IPv4 주소 설정 (e.g., 172.30.100.104)
--ip6 string IPv6 주소 설정 (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 주소 설정 (e.g., 92:d0:c6:0a:29:33)
-m, --memory bytes 사용할 메모리 크기 제한, 기본 4MB (b, k, m, g)
--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 컨테이너에 파일 시스템 마운트
--name string 컨테이너 이름 할당
--network string 네트워크 연결 (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 컨테이너의 root 파일 시스템을 읽기 전용으로 마운팅 한다.
--restart string 옵션에 따라 재시작 한다. (default "no")
# no, on-failure, on-failure:숫자, always, unless-stopped
--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 (TTY 할당)
--ulimit ulimit Ulimit options (default [])
-u, --user string 사용자 이름 또는 UID (format: <name|uid>[:<group|gid>])
--userns string 사용할 사용자 이름
--uts string UTS namespace to use
-v, --volume list <메인 OS 디렉토리>:<컨테이너 티렉토리> 공유
--volume-driver string Optional volume driver for the container
--volumes-from list Mount volumes from the specified container(s)
-w, --workdir string 컨테이너 내부 작업 디렉토리
Docker Ubuntu 16.04 컨테이너 생성해보자!!
dongdonge@dongdonge$ sudo docker run -it --name "dongdonge_ubuntu" ubuntu:16.04 /bin/bash
root@754503a85e20:/#
옵션 -it : -i 옵션은 STDIN(표준입력) 상태를 열고, -t 옵션은 tty를 확보한다.
즉, 터미널을 연결한다.
--name : 컨테이너 이름을 지정할 수 있으며, 현재 "dongdonge_ubuntu"라는 이름을 지정하였다.
하지만 도커 터미널 상태에서 "exit" 또는 "CTRL + C" 를 입력하면 도커 컨테이너 프로세스는 종료가 된다.
백그라운드 모드로 동작시키고 도커 터미널에서 나가고 싶으면 아래 키보드를 누르자!!
root@754503a85e20:/# CTRL + P
root@754503a85e20:/# CTRL + Q
dongdonge@dongdonge$
순차적으로 컨트롤 + P 누르고 컨트로 Q를 누르면 도커는 백그라운드 모드로 전환되고, 메인 OS 터미널로 나가진다.!!
또한 아래는 docker run 컨테이너 생성시 바로 백드라운드 모드로 작동 시킬 수 있다.
dongdonge@dongdonge$ sudo docker run -d --name "dongdonge_ubuntu_test" ubuntu:16.04 /bin/bash
b7a3075da2c101947fe9b86ccbc7828cb37bd62084570c57e7eff10b105d85a4
옵션 -d, --detach : 컨테이너를 백그라운드에서 실행한다.
아래는 도커를 "exit" 종료 되어도, 자동으로 재시작하는 옵션이다.
dongdonge@dongdonge$ sudo docker run -it --restart=always --name "Ubuntu_Test" ubuntu:16.04 /bash
root@cf6c89b37284:/# exit
exit
dongdonge@dongdonge$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
cf6c89b37284 ubuntu:16.04 "/bin/bash" 8 seconds ago Up 1 second
Ubuntu_Test
--restart=always 옵션을 통해 도커 컨테이너가 종료되어도, 항상 재시작을 진행한다.
Docker 컨테이너에 웹서버가 구동되고 있다면 메인 OS의 Port 번호를 컨테이너 포트 번호로 매핑을 할 수 있다.
예를 들어 메인 OS에 8085 Port를 컨테이너 Port 80 (Web Server)에 매핑할 수 있다.
dongdonge@dongdonge$ sudo docker run -d -p 1234:80 --name "dongdonge_nginx" nginx
2c6c63f308fa0e4f38985953d309b7216dc217a249e64b1cc583ac9bad910cf2
dongdonge@dongdonge$ sudo netstat -ntlp | grep 1234
tcp6 0 0 :::1234 :::* LISTEN 8428/docker-proxy
netstat 명령을 통해 메인 OS에서 1234 포트가 개방되어 있다.
위 명령을 보면 1234로 오는 포트는 도커 컨테이너 80번 포트로 매핑된걸 볼 수 있다.
Docker 컨테이너에 DNS 서버를 설정할 수 있다. 이번에는 구글 DNS 서버인 8.8.8.8로 설정해보겠습니다.
dongdonge@dongdonge$ sudo docker run --dns 8.8.8.8 -it --name "dongdonge_dns" ubuntu:16.04 /bin/bash
root@fb84076b380b:/# cat /etc/resolv.conf
search localdomain
nameserver 8.8.8.8
Docker Container에서 DNS 설정값을 확인해보면 정상적으로 8.8.8.8 (구글 서버)로 설정된걸 확인할 수 있습니다.
Docker 컨테이너 생성시 CPU / Memory 자원을 제한할 수 있다.
dongdonge@dongdonge$ sudo docker run -it --name "test_dongdonge" --cpu-shares 2048 ubuntu:16.04 /bin/bash
root@19c69e509627:/# exit
dongdonge@dongdonge$ sudo docker run -it --name "test_dongdonge22" --memory="1g" --memory-swap="2g" ubuntu:16.04 /bin/bash
root@56e999147ede:/#
옵션을 보면 cpu Default 1024에 2배인 2048을 할당 하였고, 아래 명령어는 memory 제한을 1GB, Swap은 2GB로 제한 하였다.
Docker 컨테이너 생성시 메인 OS와 컨테이너와 디렉토리를 공유할 수 있다.
dongdonge@dongdonge$ sudo docker run -v /home/dongdonge/바탕화면/test:/usr/share/nginx/html -it --name "dongdonge_vo" nginx /bin/bash
root@12183f7203bf:/#
옵션을 확인 해보면, 메인 OS의 /home/dongdonge/바탕화면/test 디렉토리를 Docker Container의 /usr/share/nginx/html으로 공유가 되었습니다.
dongdonge@dongdonge$ echo "test 1234" > 123.txt
dongdonge@dongdonge ~/바탕화면/test$ ls -la
total 12
drwxrwxr-x 2 dongdonge dongdonge 4096 6월 17 22:14 .
drwxr-xr-x 4 dongdonge dongdonge 4096 6월 17 22:11 ..
-rw-rw-r-- 1 dongdonge dongdonge 10 6월 17 22:14 123.txt
메인 OS에 "123.txt"라는 파일을 생성하여 "test 1234"라는 글을 작성하였고, Docker 컨테이너에서 해당 파일이 공유가 되었는지 확인해보도록 하겠습니다.
root@12183f7203bf:/usr/share/nginx/html# ls -la
total 12
drwxrwxr-x 2 1000 1000 4096 Jun 17 13:14 .
drwxr-xr-x 3 root root 4096 Jun 11 00:03 ..
-rw-rw-r-- 1 1000 1000 10 Jun 17 13:14 123.txt
root@12183f7203bf:/usr/share/nginx/html# cat 123.txt
test 1234
컨테이너의 공유된 경로에 접속해보면 방금 생성했던 파일이 그대로 공유된걸 확인할 수 있다.
만약 백그라운드된 컨테이너에 접속을 하고싶다면 아래 명령으로 접속할 수 있다.!!
dongdonge@dongdonge$ sudo docker attach <컨테이너명>
Docker 컨테이너 생성시 컨테이너에 환경변수를 주거나 파일에 여러개를 담아 등록할 수 있습니다.
dongdonge@dongdonge$ sudo docker run -e dongdonge=Good -it --name "dongdonge_tt" ubuntu:
16.04 /bin/bash
root@c0898601ab06:/# set | grep dongdonge
dongdonge=Good
환경변수명으로 'dongdonge'로 설정하고 값으로는 "Good"으로 설정하였을 때, Docker 컨테이너에서 set 명령으로 환경변수를 확인해보면 방금 설정한 환경변수를 확인할 수 있습니다.
Docker 컨테이너 생성시 별도로 작업 디렉토리를 할당할 수 있습니다.
dongdonge@dongdonge$ sudo docker run -w /dongdonge -it --name "dongdonge_tttt" ubuntu:16
.04 /bin/bash
root@6d0fc332cc2e:/dongdonge#
root@6d0fc332cc2e:/dongdonge# ls
컨테이너 생성 후, 자동으로 "/dongdonge" 디렉토리가 생성이되었고 작업 디렉토리로 하고 있다.
Docker start 명령으로 Docker Container를 시작할 수 있습니다. 컨테이너 시작은 컨테이너명 또는 컨테이너 식별자 (ID)를 통해 시작할 수 있습니다.
docker start <옵션> 컨테이너명 <컨테이너명...>
또는docker container start <옵션> 컨테이너명 <컨테이너명...>>
dongdonge@dongdonge$ sudo docker start --help
Usage: docker start [OPTIONS] CONTAINER [CONTAINER...]
Start one or more stopped containers
Options:
-a, --attach Attach STDOUT/STDERR and forward signals
--detach-keys string Override the key sequence for detaching a container
-i, --interactive Attach container's STDIN
아래 예시를 통해 꺼진 도커 컨테이너를 실행 해보도록 하겠습니당.
dongdonge@dongdonge$ sudo docker start dongdonge_tt dongdonge_tttt
dongdonge_tt
dongdonge_tttt
"dongdonge_tt" 도커 이미지와 "dongdonge_tttt" 도커 이미지를 구동을 시작한다.
dongdonge@dongdonge$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f2f2fac3ebf2 nginx "/bin/bash" 29 minutes ago Up 29 minutes 0.0.0.0:3333->80/tcp nginx_test
6d0fc332cc2e ubuntu:16.04 "/bin/bash" 39 minutes ago Up About a minute
dongdonge_tttt
c0898601ab06 ubuntu:16.04 "/bin/bash" 42 minutes ago Up About a minute
dongdonge_tt
구동된 컨테이너가 정상적으로 실행된 리스트를 확인할 수 있습니당.
Docker stop 명령으로 실행중인 컨테이너를 중지할 수 있습니다. 만약 컨테이너를 삭제하려면 해당 동작중인 컨테이너를 먼저 정지시키고, 삭제를 해야 합니다.
컨테이너 재시작은 아래 명령 'restart' 통해 가능합니다.
docker restart <컨테이너명>
docker stop <옵션> 컨테이너명 <컨테이너명...>
또는docker container stop <옵션> 컨테이너명 <컨테이너명...>>
dongdonge@dongdonge$ sudo docker stop --help
Usage: docker stop [OPTIONS] CONTAINER [CONTAINER...]
Stop one or more running containers
Options:
-t, --time int Seconds to wait for stop before killing it (default 10)
만약 모든 컨테이너를 중지하길 원한다면 아래 명령을 통해 실행중인 모든 컨테이너를 중지할 수 있다.
dongdonge@dongdonge$ sudo docker stop $(sudo docker ps -a -q)
0e5851f85ecd
6ef5dff6d602
Docker rm 명령으로 컨테이너를 삭제할 수 있다. 하지만 삭제는 컨테이너가 정지되어 있어야 가능하다.
docker rm <옵션> 컨테이너명 <컨테이너명...>
또는docker container rm <옵션> 컨테이너명 <컨테이너명...>>
dongdonge@dongdonge$ sudo docker rm --help
Usage: docker rm [OPTIONS] CONTAINER [CONTAINER...]
Remove one or more containers
Options:
-f, --force Force the removal of a running container (uses SIGKILL)
-l, --link Remove the specified link
-v, --volumes Remove the volumes associated with the container
dongdonge@dongdonge$ sudo docker rm 0e5851f85ecd -f
0e5851f85ecd
위 옵션에 -f 추가하여 강제로 도커 컨테이너를 삭제할 수 있다.
모든 컨테이너를 삭제하고 싶다면 아래 명령어를 참조하자.
dongdonge@dongdonge$ sudo docker stop $(sudo docker ps -a -q)
6ef5dff6d602
dongdonge@dongdonge$ sudo docker rm $(sudo docker ps -a -q)
6ef5dff6d602
위 명령어를 통해 모든 컨테이너를 정지시키고, 컨테이너 전체를 삭제한다.
물론 삭제 작업이므로 항상 백업 및 중요한 파일이 삭제되지 않도록 조심하자.