Update docker-image.yml #5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Deploy to AWS EC2 using Docker - PATATA | |
on: | |
push: | |
branches: | |
- develop | |
pull_request: | |
branches: | |
- develop | |
env: | |
DOCKER_IMAGE_NAME: ${{ secrets.DOCKER_IMAGE_NAME }} | |
EC2_HOST: ${{ secrets.EC2_HOST }} | |
PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }} | |
jobs: | |
build-and-push-docker: | |
runs-on: ubuntu-latest | |
if: github.event.pull_request.merged == true && github.event.pull_request.base.ref == 'develop' || github.event_name == 'push' && github.ref == 'refs/heads/develop' && github.event.head_commit.message != 'Merge pull request' | |
# develop 브랜치로의 pull request가 merge 되었을 때 github actions 작동 | |
# 또는 develop 브랜치에 push가 발생하면 github actions 작동 (pr merge시 actions가 2번 발생하는 문제를 해결하기 위해 merge가 아닌 push때만 실행되도록 함) | |
steps: | |
- name: Checkout | |
uses: actions/checkout@v4 | |
- name: Set up JDK 17 | |
uses: actions/setup-java@v4 | |
with: | |
java-version: '17' | |
distribution: 'temurin' | |
- name: Set up application-database.yml | |
run: echo "${{ secrets.APPLICATION }}" > ./src/main/resources/application.yml | |
- name: Grant execute permission for gradlew | |
run: chmod +x ./gradlew | |
- name: Setup Gradle | |
uses: gradle/actions/setup-gradle@af1da67850ed9a4cedd57bfd976089dd991e2582 # v4.0.0 | |
- name: Build with Gradle | |
run: ./gradlew build -x test | |
- name: Build the Docker image | |
run: docker build --platform linux/amd64 -t ${{ env.DOCKER_IMAGE_NAME }} | |
- name: Login to Docker Hub using Access Token | |
run: echo "${{ secrets.DOCKER_HUB_TOKEN }}" | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin | |
- name: Push the Docker image | |
run: docker push ${{ env.DOCKER_IMAGE_NAME }} | |
deploy-to-ec2: | |
needs: build-and-push-docker | |
runs-on: ubuntu-latest | |
steps: | |
- name: Deploy to EC2 | |
uses: appleboy/ssh-action@master | |
with: | |
host: ${{ env.EC2_HOST }} | |
username: ubuntu | |
port: 22 | |
key: ${{ env.PRIVATE_KEY }} | |
script: | | |
cd /home/ubuntu/ | |
sudo chmod 666 /var/run/docker.sock | |
sudo docker stop $(docker ps -a -q) | |
sudo docker rm -f $(docker ps -qa) | |
sudo docker pull ${{ env.DOCKER_IMAGE_NAME }} | |
sudo docker run -d -p 80:8080 -e TZ=Asia/Seoul ${{ env.DOCKER_IMAGE_NAME }} | |
sudo docker image prune -f |