클라우드의 장점을 최대한 활용하여 정보시스템을 구축 및 실행하는 환경
클라우드 네이티브 기술은 조직이 퍼블릭, 프라이빗, 그리고 하이브리드 클라우드와 같은 현대적이고 동적인 환경에서 확장 가능한 애플리케이션을 개발하고 실행할 수 있게 해준다. 컨테이너, 서비스 메쉬, 마이크로서비스, 불변(Immutable) 인프라, 그리고 선언형(Declarative) API가 이러한 접근 방식의 예시들이다.
이 기술은 회복성, 관리 편의성, 가시성을 갖춘 느슨하게 결합된 시스템을 가능하게 한다. 견고한 자동화 기능을 함께 사용하면, 엔지니어는 영향이 큰 변경을 최소한의 노력으로 자주, 예측 가능하게 수행할 수 있다.
Cloud Native Computing Foundation은 벤더 중립적인 오픈 소스 프로젝트 생태계를 육성하고 유지함으로써 해당 패러다임 채택을 촉진한다. 우리 재단은 최신 기술 수준의 패턴을 대중화하여 이런 혁신을 누구나 접근 가능하도록 한다.
서버
, REST API
, CLI
를 포함도커 이미지를 생성하고 관리하는 dockerd라는 서버.
데몬에 명령을 보내는 역할
도커 이미지 저장소
repository는 registry(시스템) 보다 작은 개념
run 아주 많이 쓸 것 !!
도커 이미지를 찍으려면 컨테이너를 커밋해야 찍힘
도커파일을 정의하면 그걸 토대로 빌드하면 이미지가 생긴다.
=> 빌드를 더 많이 한다.
cp로 파일을 주고 받을 수 있다
C:\Users\myanj> docker help
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Common Commands:
run Create and run a new container from an image
exec Execute a command in a running container
ps List containers
build Build an image from a Dockerfile
pull Download an image from a registry
push Upload an image to a registry
images List images
login Authenticate to a registry
logout Log out from a registry
search Search Docker Hub for images
version Show the Docker version information
info Display system-wide information
Management Commands:
ai* Ask Gordon - Docker Agent
builder Manage builds
buildx* Docker Buildx
compose* Docker Compose
container Manage containers
context Manage contexts
debug* Get a shell into any image or container
desktop* Docker Desktop commands (Beta)
dev* Docker Dev Environments
extension* Manages Docker extensions
feedback* Provide feedback, right in your terminal!
image Manage images
init* Creates Docker-related starter files for your project
manifest Manage Docker image manifests and manifest lists
network Manage networks
plugin Manage plugins
sbom* View the packaged-based Software Bill Of Materials (SBOM) for an image
scout* Docker Scout
system Manage Docker
trust Manage trust on Docker images
volume Manage volumes
Swarm Commands:
swarm Manage Swarm
Commands:
attach Attach local standard input, output, and error streams to a running container
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
export Export a container's filesystem as a tar archive
history Show the history of an image
import Import the contents from a tarball to create a filesystem image
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
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
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
rmi Remove one or more images
save Save one or more images to a tar archive (streamed to STDOUT by default)
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
wait Block until one or more containers stop, then print their exit codes
Global Options:
--config string Location of client config files (default
"C:\\Users\\myanj\\.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 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
"C:\\Users\\myanj\\.docker\\ca.pem")
--tlscert string Path to TLS certificate file (default
"C:\\Users\\myanj\\.docker\\cert.pem")
--tlskey string Path to TLS key file (default
"C:\\Users\\myanj\\.docker\\key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit
Run 'docker COMMAND --help' for more information on a command.
For more help on how to use Docker, head to https://docs.docker.com/go/guides/
Docker 참고 자료
Dockerfile: 도커 이미지를 생성(빌드)하는데 필요한 명령어를 순서대로 기술한 텍스트 파일
이미지 빌드 명령어: docker build, docker builder build, docker image build, docker buildx build
main.go
/* 8080 포트로 HTTP 요청을 대기하다가, /로 요청이 들어오면 Hello Docker!!!를 응답 */
/* 프로그램의 진입점인 main 패키지를 지정 */
package main
/* 표준 입출력과 문자열 형식을 처리하는 Go 패키지,
로그를 출력하기 위한 패키지,
HTTP 서버와 클라이언트 관련 기능을 제공하는 패키지를 임포트 */
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Println("received request")
fmt.Fprintf(w, "Hello Docker!!")
})
log.Println("start server")
server := &http.Server{Addr: ":8080"}
if err := server.ListenAndServe(); err != nil {
log.Println(err)
}
}
go 다운로드 및 설치
https://go.dev/dl/
go run main.go
동일 애플리케이션을 다른 서버(PC)에서 실행해야 한다면, #1 ~ #2 과정을 반복해야 함
⇒ 애플리케이션과 애플리케이션 실행에 필요한 환경(go)을 묶어서 배포하는 것이 필요
⇒ 컨테이너를 이용해서 가능
FROM golang:1.23.6
RUN mkdir /goapp
COPY main.go /goapp
CMD ["go", "run", "/goapp/main.go"]
도커 실행하면서
docker buildx build -t example/echo:latest .
-t : tagging 이미지의 이름 정하기
. : 현재 디렉토리 <= Dockerfile의 위치
=> [1/3] FROM docker.io/library/golang:1.23.6@sha2 42.6s
~~~~~~~~~ ~~~~~~~ ~~~~~~ ~~~~~~
| | | |
| | | +-- tag -> 생략하면 latest
| | +-- image name
| +-- repository
+-- registry
...
=> [2/3] RUN mkdir /goapp 2.2s
=> [3/3] COPY main.go /goapp 0.1s
=> exporting to image 0.1s
docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
example/echo latest cecb6a160ec2 13 minutes ago 838MB
docker image ls --no-trunc
⇐ 전체 해시 값(ID) 확인 (안 줄임)
REPOSITORY TAG IMAGE ID
CREATED SIZE
example/echo latest sha256:cecb6a160ec2e7b5ccb5ade209f84b4c65ddaed8c4daa68a0fdba30f5d9ff950 15 minutes ago 838MB
docker container run -d -p 8282:8080
example/echo:latest
3263089e0b6a724db0e9ffb855000f2a57b0d387db136f9ba7ca858b10f9c342 ⇐ 컨테이너 ID
docker container ls
⇐ 실행 상태의 컨테이너를 조회
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3263089e0b6a example/echo:latest "go run /goapp/main.…" 10 seconds ago Up 9 seconds 0.0.0.0:8282->8080/tcp elegant_vaughan
curl http://localhost:8282
Hello Docker!! ⇐ 컨테이너 내부에서 실행되고 있는 애플리케이션의 응답
docker image push example/echo:latest
The push refers to repository [docker.io/example/echo]
5ae71dd3108f: Preparing
9e90da5b04bc: Preparing
5f70bf18a086: Preparing
6422f5afca27: Preparing
727ecdde08c3: Preparing
1299c97d7d50: Waiting
41d4dc7516bb: Waiting
c0f51bbdc37d: Waiting
91b542912d12: Waiting
denied: requested access to the resource is denied
docker image tag example/echo:latest 본인의 도커 허브 계정명/echo:latest
docker image ls
docker image push letthem/echo:latest
docker container run -d -p 9999:8080 myanjini/echo:latest
712b12082f3353e181bb522a5ba87ed78907764195cfc3ed8d20871042ae8663
docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
712b12082f33 myanjini/echo:latest "go run /goapp/main.…" 14 seconds ago Up 14 seconds 0.0.0.0:9999->8080/tcp zen_volhard
6fed7975d997 cecb6a160ec2 "go run /goapp/main.…" 31 minutes ago Up 31 minutes 0.0.0.0:8282->8080/tcp mystifying_neumann
curl http://localhost:9999
Hello Docker!! ^..^
Layered Architecture : 바뀐 layer만 가져와서 실행하므로 빠르다 !!
docker container run -p 8080 myanjini/echo:latest
-d
- -d : 컨테이너를
detach
모드로백그라운드
로(데몬으로) 실행된다. 컨테이너에서 go run main.go 가 정상적으로 됐는지 안 됐는지 관계없이 바로 run 하는 것 (비동기
방식)- -d 제거 :
attach
모드로포그라운드
로 실행된다. 호출된 상태에서 끝나야 return 되어 run할 수 있게 날아온다. (동기
방식) => 다른 작업을 못 하고 실수로 닫아도 죽으니 통제할 수가 없다 ㅜ.ㅜ 별도의 창을 통해서만 제어할 수 있다. 불편하다. 그럼 왜 쓸까? 개발할 때 출력되는 로그들을 확인(디버깅 용이)하기 위해서 사용한다.
PS C:\Users\myanj> docker container ls CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
db5eec2eff3c myanjini/echo:latest "go run /goapp/main.…" 5 minutes ago Up 5 minutes 0.0.0.0:62772->8080/tcp infallible_ganguly
0f4bfe0be8b9 myanjini/echo:latest "go run /goapp/main.…" 14 minutes ago Up 14 minutes 0.0.0.0:62361->8080/tcp dreamy_hofstadter
712b12082f33 myanjini/echo:latest "go run /goapp/main.…" 23 minutes ago Up 23 minutes 0.0.0.0:9999->8080/tcp zen_volhard
6fed7975d997 cecb6a160ec2 "go run /goapp/main.…" 54 minutes ago Up 54 minutes 0.0.0.0:8282->8080/tcp mystifying_neumann
PS C:\Users\myanj> curl http://localhost:62772
StatusCode : 200
StatusDescription : OK
Content : Hello Docker!! ^..^
RawContent : HTTP/1.1 200 OK
Content-Length: 19
Content-Type: text/plain; charset=utf-8
Date: Tue, 11 Feb 2025 05:40:45 GMT
Hello Docker!! ^..^
Forms : {}
Headers : {[Content-Length, 19], [Content-Type, text/plain; charset=utf-8], [Date, Tue, 11 Feb 2025 05:40:45 GMT]}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 19
컨테이너를 실행한 원래 터미널을 확인하면 요청 로그가 출력되는 것을 확인할 수 있음
c:\docker\go> docker container run -p 8080 myanjini/echo:latest
2025/02/11 05:35:20 start server
2025/02/11 05:40:45 received request
got 3 SIGTERM/SIGINTs, forcefully exiting ⇐ Ctrl + C를 세 번 전달 ⇒ detach 모드로 전환
c:\docker\go> docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
db5eec2eff3c myanjini/echo:latest "go run /goapp/main.…" 9 minutes ago Up 9 minutes 0.0.0.0:62772->8080/tcp infallible_ganguly
0f4bfe0be8b9 myanjini/echo:latest "go run /goapp/main.…" 19 minutes ago Up 19 minutes 0.0.0.0:62361->8080/tcp dreamy_hofstadter
712b12082f33 myanjini/echo:latest "go run /goapp/main.…" 27 minutes ago Up 27 minutes 0.0.0.0:9999->8080/tcp zen_volhard
6fed7975d997 cecb6a160ec2 "go run /goapp/main.…" 58 minutes ago Up 58 minutes 0.0.0.0:8282->8080/tcp mystifying_neumann
docker container rm 컨테이너 식별자
컨테이너ID가 d로 시작하는 컨테이너가 하나인 경우
docker container rm d
Error response from daemon: cannot remove container "/infallible_ganguly": container is running: stop the container before removing or force remove ⇐ 삭제하려고 하는 컨테이너가 실행 상태인 경우 삭제가 불가능
docker container rm -f d
⇐ -f 옵션을 이용해서 강제로 삭제
docker container ls
⇐ infallible_ganguly 이름의 컨테이너가 삭제된 것을 확인
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0f4bfe0be8b9 myanjini/echo:latest "go run /goapp/main.…" 25 minutes ago Up 25 minutes 0.0.0.0:62361->8080/tcp dreamy_hofstadter
712b12082f33 myanjini/echo:latest "go run /goapp/main.…" 33 minutes ago Up 33 minutes 0.0.0.0:9999->8080/tcp zen_volhard
6fed7975d997 cecb6a160ec2 "go run /goapp/main.…" About an hour ago Up About an hour 0.0.0.0:8282->8080/tcp mystifying_neumann
docker container ls -a
<= 모든 컨테이너를 가져옴 (-a = --all)
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0b647fd83cfe myanjini/echo:latest "go run /goapp/main.…" 3 hours ago Up 3 hours 0.0.0.0:9997->8080/tcp jovial_darwin
d61e479ea7a5 myanjini/echo:latest "go run /goapp/main.…" 3 hours ago Up 3 hours 0.0.0.0:9999->8080/tcp hardcore_bartik
3263089e0b6a example/echo:latest "go run /goapp/main.…" 4 hours ago Up 4 hours 0.0.0.0:8282->8080/tcp elegant_vaughan
docker container ls -a -q
<= 모든 id를 가져옴 (-a -q = -aq)
0f4bfe0be8b9
712b12082f33
6fed7975d997
docker container rm -f $(docker container ls -aq)
<= 모든 상태의 컨테이너를 강제로 삭제
docker container ls -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
docker container run --name sm -d -p 80:8080 pengbai/docker-supermario
docker container logs sm
⇐ 컨테이너 로그를 확인
localhost:80
접속
docker container attach sm
해당 컨테이너는 쉘을 제공하지 않기 때문에 다른 작업이 불가 😭
Ctrl + C : 컨테이너를 실행할 때 실행한 프로세스를 종료 ⇒ 컨테이너가 종료됐다.
docker container ls -a
<= 죽은 컨테이너까지 보여줌
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c84974b74c76 pengbai/docker-supermario "catalina.sh run" 14 minutes ago Exited (130) About a minute ago sm
docker container start sm
⇐ 중지 상태의 컨테이너를 다시 시작시켜주기
sm
docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c84974b74c76 pengbai/docker-supermario "catalina.sh run" 16 minutes ago Up 5 seconds 0.0.0.0:80->8080/tcp sm
docker container exec -it sm /bin/bash
mario@c84974b74c76:/usr/local/tomcat$
⇐ 컨테이너 내부에 /bin/bash가 실행된 결과
set | grep HOSTNAME
⇐ HOSTNAME이라는 환경변수의 값을 읽어온다. 컨테이너 ID와 같다. (HOSTNAME이 무엇인지 확인용)
mario@c84974b74c76:/usr/local/tomcat$ exit
docker container cp sm:/usr/local/tomcat/webapps/ROOT /Users/letthem/Desktop/letthems/study/docker/
cd c:\docker
dir
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2025-02-11 오후 1:21 go
d----- 2019-09-19 오전 1:11 ROOT
cd ROOT
code .
\docker\ROOT\index.html 파일 내용을 수정
<!DOCTYPE html>
<html>
<head>
<title>Infinite Mario - JavaScript ^..^</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
docker container cp index.html sm:/usr/local/tomcat/webapps/ROOT/
docker container run -d -p 8081:80 nginx
4b69150841f69b1d5ef134f2bd3be8bbb6fc8dc6ba5e5c103a06490c14387cd6
docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b21d6886a6dd nginx "/docker-entrypoint.…" 40 seconds ago Up 38 seconds 0.0.0.0:8081->80/tcp wonderful_gagarin
721d13c8c2b5 pengbai/docker-supermario "catalina.sh run" 20 minutes ago Up 13 minutes 0.0.0.0:80->8080/tcp sm
docker container exec 4b69 ls /usr/share/nginx/html
50x.html
index.html
docker container cp . b21d:/usr/share/nginx/html/
Successfully copied 1.82MB to b21d:/usr/share/nginx/html/
docker container exec b21d ls -l /usr/share/nginx/html
명령어 쉘로 들어가서 내부에 직접 진입하고 싶으면 -it /bin/bash까지 붙여줘야 하는데
여기서는 외부에서 단순 list 읽기이므로 -it /bin/bash 이런 거 없이 ls -l 을 써줬다.
total 128
-rw-r--r-- 1 root root 497 Feb 5 11:06 50x.html
drwxr-xr-x 2 501 dialout 4096 Sep 18 2019 Enjine
-rw-r--r-- 1 501 dialout 364 Sep 18 2019 README
drwxr-xr-x 2 501 dialout 4096 Sep 18 2019 code
-rw-r--r-- 1 501 dialout 9518 Sep 18 2019 enjine.min.js
-rw-r--r-- 1 501 dialout 929 Sep 18 2019 flipTest.html
drwxr-xr-x 2 501 dialout 4096 Sep 18 2019 images
-rw-r--r-- 1 501 dialout 2786 Feb 11 08:46 index.html
-rw-r--r-- 1 501 dialout 78796 Sep 18 2019 mario.min.js
-rw-r--r-- 1 501 dialout 569 Sep 18 2019 minTest.html
drwxr-xr-x 2 501 dialout 4096 Sep 18 2019 sounds
=> 이렇게 하면 nginx 내부에 index.html
이 있는 걸 확인할 수 있다.
현재 이 루트에 있는 마리오 파일들을 copy해서 nginx의 기본 Web Root Directory로 싹 다 복사한 것이다.
Dockerfile
.dockerignore
README
FROM nginx
COPY . /usr/share/nginx/html/
FROM
: base imageCOPY . /usr/share/nginx/html/
: 현재 디렉토리에 있는 모든 파일을 nginx 컨테이너 내부의 html 디렉토리에 copydocker image build -t letthem/supermario:v1 .
docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
letthem/supermario v1 ec70b77050d9 15 seconds ago 284MB
docker container run -d -p 80 letthem/supermario:v1
c696aaf07a5a28591a9cbf2ad35f647fd5520be72247557748ee41c7e50737bd
docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c696aaf07a5a letthem/supermario:v1 "/docker-entrypoint.…" 12 seconds ago Up 11 seconds 0.0.0.0:52931->80/tcp stoic_brown
b21d6886a6dd nginx "/docker-entrypoint.…" 16 minutes ago Up 16 minutes 0.0.0.0:8081->80/tcp wonderful_gagarin
721d13c8c2b5 pengbai/docker-supermario "catalina.sh run" 36 minutes ago Up 28 minutes
146 페이지에 있는 Dockerfile 명령어를 https://pyrasis.com/jHLsAlwaysUpToDateDocker 사이트에 상세 설명을 정독해보자 !