Python 프레임워크인 FastAPI로 작성된 API 서버를 Gitlab CI/CD를 이용하여 Docker 이미지로 자동 빌드, 배포하는 방법을 기록합니다.
0. 환경 및 실행 흐름
- 개발 환경 : Windows 10 / Python 3.10 / FastAPI 0.72.0
- 배포 서버 OS : Ubuntu 20.04.3 LTS / Docker 20.10.12 Community
1. Docker에 Gitlab-Runner, DinD Container 실행
# 1. Gitlab-Runner Image pull
sudo docker pull gitlab/gitlab-runner:latest
# 2. Check Image
sudo sudo docker image ls -a
# 3. Create Gitlab Runner Network
sudo docker network create gitlab-runner-net
# 4. Run Gitlab Runner 1 Container in Gitlab Runner Network
sudo docker run -d --name gitlab-runner-1 --restart always \
--network gitlab-runner-net -v /var/run/docker.sock:/var/run/docker.sock \
gitlab/gitlab-runner
# 5. Run DinD Container in Gitlab Runner Network
sudo docker run -d --name gitlab-dind --privileged --restart always \
-p 2375:2375 --network gitlab-runner-net -v /var/lib/docker docker:dind
2. Gitlab Repository에 Gitlab-Runner 등록
# 1. Exec gitlab-runner-1
sudo docker container exec -it gitlab-runner-1 bash
# 2. (In Container)Regist Runner
gitlab-runner register -n --url {Your Gitlab URL} \
--registration-token {Your Token} \
--description {Your Desc} \
--tag-list {Your Tags} \
--executor docker \
--docker-privileged \
--docker-image docker:stable
3. 프로젝트 설정 (.gitlab-ci.yml & Dockerfile)
1) 참고 - 프로젝트 구조
2) gitlab-ci.yml
### .gitlab-ci.yml ###
image: docker:stable
variables:
IMAGE_NAME: {Your Image Name}:$CI_COMMIT_SHA
services:
- name: docker:dind
stages:
- test
- package
- deploy
test:
stage: test
only:
# 설정된 Branch만 Runner가 선별적으로 실행 함
- master
tags:
# 설정된 Tag를 Runner가 선별적으로 실행 함
- {Your Tag}
script:
# Runner Excutor
- echo "Hello, $GITLAB_USER_LOGIN! You're now in test phase"
# Image Name
- echo "Will make $IMAGE_NAME, Good luck!"
# Check Docker Info
- docker info
docker-build:
stage: package
only:
- master
tags:
- {Your Tag}
script:
# Check Package
- ls -al
- docker container ls -a
# Build Docker Image
- docker build . -t $IMAGE_NAME
# Check Your Docker Image
- docker images | grep '{Your Image Name}'
deploy:
stage: deploy
only:
- master
tags:
- {Your Tag}
script:
- docker container ls -a
# Remove last Container
- docker container rm -f {Your Container Name}
# Run New Container with 8000
- docker run -d -p 8000:8000 --name {Your Container Name} --restart always $IMAGE_NAME
- docker container ls -a
3) Dockerfile
### Dockerfile ###
FROM python:3.10
WORKDIR /prod
COPY ./log.ini /prod/log.ini
COPY ./requirements.txt /prod/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /prod/requirements.txt
COPY ./app /prod/app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "10", "--log-config", "log.ini"]
4. 결과 및 확인
'프로그래밍 > Linux.' 카테고리의 다른 글
[Docker] DIND 빌드가 너무 느린 경우 시도해 볼만한 방법 (0) | 2023.06.22 |
---|---|
[Docker] Docker 설치(Redmine 과 MySQL을 곁들인) (0) | 2021.06.28 |
[WSL2] WSL2 에 설치된 Linux 배포판 삭제하기 (0) | 2021.05.02 |
[WSL2] WSL2 환경에서 Linux 배포판 설치하기 (0) | 2021.05.02 |
댓글