파이썬

 

✅ 최종 목표 요약

  1. Django 앱 테스트

  2. Docker 이미지 빌드

  3. 원격 서버로 SSH 접속 및 배포

  4. 서비스 재시작

 

 

1. Dockerfile 설정

Django + Gunicorn을 컨테이너로 실행하기 위한 기본 Dockerfile입니다:

 

# 베이스 이미지
FROM python:3.12-slim

# 작업 디렉토리 설정
WORKDIR /app

# 의존성 복사 및 설치
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 앱 복사
COPY . .

# 환경 변수 설정 (Docker 내부에서 사용할 기본 값)
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Gunicorn으로 앱 실행
CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000"]

 

config.wsgi:application에서 config는 wsgi.py가 있는 Django 프로젝트 폴더 이름입니다. 적절히 변경하세요.

 

 

 

 

2. systemd 서비스 설정 (python.service 예시)

서버에 아래 경로에 .service 파일을 생성합니다:

# /etc/systemd/system/python.service

[Unit]
Description=Django Docker Container
After=docker.service
Requires=docker.service

[Service]
Restart=always
ExecStart=/usr/bin/docker start -a django-app
ExecStop=/usr/bin/docker stop django-app

[Install]
WantedBy=multi-user.target

 

적용 방법

sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl enable python.service
sudo systemctl start python.service

 

이 서비스는 GitHub Actions에서 Docker 컨테이너를 수동으로 갱신한 뒤, restart 명령으로 재시작됩니다.

 

 

3. Nginx 설정 (Proxy + Gunicorn)

# /etc/nginx/sites-available/django_app

server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://127.0.0.1:1234;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /static/ {
        alias /home/python/app/static/;
    }

    location /media/ {
        alias /home/python/app/media/;
    }
}

 

 

적용 명령

sudo ln -s /etc/nginx/sites-available/django_app /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

 

 

4. Gunicorn requirements.txt 포함 여부 확인

requirements.txt에는 반드시 Gunicorn 포함되어야 합니다:

 

Django==5.2.1
djangorestframework>=3.14
asgiref==3.8.1
sqlparse==0.5.3
gunicorn

# ORM 및 DB
# psycopg2-binary  # PostgreSQL
# mysqlclient      # MySQL

# 개발 도구
pytest
pytest-django
python-dotenv
django-debug-toolbar

 

 

 

5. 디렉토리 구조 예시

project-root/
├── manage.py
├── config/
│   ├── __init__.py
│   ├── settings.py
│   ├── wsgi.py
│   └── urls.py
├── app/
│   └── ...
├── static/
├── media/
├── Dockerfile
└── requirements.txt

 

 

구성 요소목적

GitHub Actions                        CI/CD 자동화

Dockerfile                                Django + Gunicorn 이미지 빌드

systemd                                  서버 부팅 시 자동 시작

Nginx                                              외부 요청 → 컨테이너 연결

Gunicorn                               Django WSGI 서버

 

 

 

 

 

1. ssh 설정 및 기타 설정 다음참조

1)  https://macaronics.net/m01/spring/view/2422

 

2)  https://macaronics.net/m03/nodejs/view/2423

 

 

 docker-django.yml 

name: Django CI/CD with Docker and SSH

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3

      - uses: actions/setup-python@v4
        with:
          python-version: '3.12.3'

      - name: ✅ Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt

      - name: ????️ Create .env file from secrets.ENV
        run: echo "${{ secrets.ENV }}" > .env

      - name: ✅ Make migrations
        run: python manage.py makemigrations

      - name: ✅ Migrate database
        run: python manage.py migrate

      - name: ✅ Run tests
        run: python manage.py test

      - name: ✅ Build Docker image
        run: docker build -t django-app .

      - name: ✅ Set up SSH
        uses: webfactory/ssh-agent@v0.9.0
        with:
          ssh-private-key: ${{ secrets.DEPLOY_KEY }}

      - name: ✅ Deploy to remote server via SSH
        run: |
          ssh -o StrictHostKeyChecking=no ${{ secrets.USER }}@${{ secrets.HOST }} << 'EOF'
            set -e
            echo "✅ Switching to project directory"
            cd ${{ secrets.TARGET_DIR }}

            echo "✅ Cleaning old containers/images"
            docker stop django-app || true && docker rm django-app || true
            docker rmi django-app || true

            echo "✅ Pulling latest code"
            git pull origin main

            echo "✅ Writing .env file"
            echo "${{ secrets.ENV }}" > .env

            echo "✅ Building Docker image"
            docker build -t django-app .

            echo "✅ Starting Docker container"
            docker run -d --name django-app --env-file .env -p ${{ secrets.PORT }}:8000 django-app

            echo "✅ Restarting service if needed"
            sudo systemctl restart ${{ secrets.SERVICE_NAME }} || true
          EOF

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  라이트

새로운 친구를 사귀되, 옛친구를 소중히 하라

댓글 ( 0)

댓글 남기기

작성

파이썬 목록    more