이 포스팅은 Google Cloud에서 제공하는 'Kubernetes in Google Cloud' 교육을 기반으로 실습하고 내용을 작성하였습니다.
Docker 란?
- Docker는 애플리케이션을 개발, 출시, 실행하는 데 사용하는 개방형 플랫
- Docker를 사용하면 인프라에서 애플리케이션을 분리하고 인프라를 관리형 애플리케이션처럼 취급
- Docker는 코드를 더욱 빠르게 출시, 테스트, 배포하고 코드 작성과 실행 주기를 단축
- Docker 컨테이너는 Kubernetes에서 직접 사용할 수 있어 GCP의 Kubernetes Engine에서 쉽게 실행
Step 1. Docker Hub의 공개 이미지를 기반으로 컨테이너 실행
- Cloud Shell을 열고 hello world 컨테이너를 실행
docker run hello-world
(명령어 결과)
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
9db2ca6ccae0: Pull complete
Digest: sha256:4b8ff392a12ed9ea17784bd3c9a8b1fa3299cac44aca35a85c90c5e3c7afacdc
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
...
이 명령어 실행시 화면에 Hello from Docker!를 반환합니다.
Docker 데몬이 hello-world 이미지를 검색했으나 로컬에서 이미지를 찾지 못했고, Docker Hub라는 공개 레지스트리에서 이미지를 가져오고, 가져온 이미지에서 컨테이너를 생성하고, 컨테이너를 실행합니다.
2. 컨테이너 이미지 확인
docker images
docker run hello-world
Step 2. 컨테이너 이미지 빌드
간단한 노드 애플리케이션이 기반인 Docker 이미지를 빌드해보았습니다.
1. test 폴더 만들어 이동
mkdir test && cd test
2. Dockerfile 생성
cat > Dockerfile <<EOF
# Use an official Node runtime as the parent image
FROM node:lts
# Set the working directory in the container to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
ADD . /app
# Make the container's port 80 available to the outside world
EXPOSE 80
# Run app.js using node when the container launches
CMD ["node", "app.js"]
EOF
- FROM node:lts //기본 상위 이미지 지정
- WORKDIR /app //컨테이너의 현재 작업 디렉토리 설정
- APP ./app //현재 디렉토리로 컨테이너 추가
- EXPOSE 80 //컨테이너 포트 공개 & 연결 허용
- CMD ["node", "app.js"] //애플리케이션 시작
3. 노드 애플리케이션 생성
cat > app.js <<EOF
const http = require('http');
const hostname = '0.0.0.0';
const port = 80;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log('Server running at http://%s:%s/', hostname, port);
});
process.on('SIGINT', function() {
console.log('Caught interrupt signal and will exit');
process.exit();
});
EOF
포트 80에서 수신 대기하고 'Hello World'를 반환하는 간단한 HTTP 서버
4. 이미지 빌드
docker build -t node-app:0.1 .
Dockerfile이 있는 디렉터리에서 실행에 주어야 함 주의!
5. 빌드 이미지 확인
docker images
결과로 반환되는 것들을 보면,
- node: 기본 이미지
- node-app: 빌드한 이미지
Step 3. 컨테이너 실행
1. 포트 매핑
docker run -p 4000:80 --name my-app node-app:0.1
- --name 플래그: 컨테이너 이름을 지정
- -p: Docker가 컨테이너의 포트 80에 호스트의 포트 4000을 매핑하도록 지시하는 플래그
=> 이제 http://localhost:4000에서 서버에 접속할 수 있게 됐습니다!
만약 포트 매핑을 하지 않으면 localhost에서 접속할 수 없습니다.
- 다른 터미널을 열고 curl http://localhost:4000 을 실행해보면 'Hello World'가 정상적으로 나옴을 볼 수 있습니다.
2. 백그라운드 실행 설정
초기 터미널이 실행되는 동안 컨테이너가 실행되는 것입니다.
그래서 컨테이너를 터미널 세션에 종속시키지 않고 백그라운드에서 실행하려면 -d 플래그를 지정하면 됩니다!
1) 초기 터미널을 닫고 컨테이너를 중지하고 삭제
docker stop my-app && docker rm my-app
2) 백그라운드에서 시작
docker run -p 4000:80 --name my-app -d node-app:0.1
docker ps
Step 4. Google Artifact Registry로 푸시
1. Artifact Registry > 저장소로 이동해 형식이 'Docker'인 저장소 생성
2. 인증 구성
Docker가 Artifact Registry에 대한 요청을 인증하는 데 CLI를 사용하도록 구성해야 하는 과정이 필요합니다.
gcloud auth configure-docker us-central1-docker.pkg.dev
3. 푸시
export PROJECT_ID=$(gcloud config get-value project)
cd ~/test
프로젝트 ID를 설정하고 Dockerfile이 포함된 디렉터리로 변경합니다.
docker build -t us-central1-docker.pkg.dev/$PROJECT_ID/my-repository/node-app:0.2 .
node-app:0.2에 태그를 지정합니다.
docker push us-central1-docker.pkg.dev/$PROJECT_ID/my-repository/node-app:0.2
이미지를 Artifact Registry로 푸시합니다.
빌드가 완료되면 Artifact Registry 콘솔에서 node-app이라는 이름의 Docker 컨테이너가 생성되었음을 볼 수 있습니다!
'Cloud' 카테고리의 다른 글
[GCP/Kubernetes] Kubernetes를 통해 클라우드 조정하기 (0) | 2023.05.11 |
---|---|
[GCP/Kubernetes] Kubernetes Engine에 컨테이너 애플리케이션 배포하기 (0) | 2023.05.11 |