Skip to content

Workflow file for this run

name: Deploy to Amazon EC2
on:
push:
branches: [ "main" ]
env:
AWS_REGION: ap-southeast-1
CONTAINER_NAME: darthmalgus/basic-go-service
permissions:
contents: read
jobs:
deploy:
name: Deploy
runs-on: ubuntu-latest
environment: production
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
- name: Build, tag, and push image to Docker Hub
id: build-image
env:
IMAGE_TAG: ${{ github.sha }}
run: |
docker build -t $CONTAINER_NAME:$IMAGE_TAG .
docker push $CONTAINER_NAME:$IMAGE_TAG
echo "image=$CONTAINER_NAME:$IMAGE_TAG" >> $GITHUB_OUTPUT
- name: Deploy to EC2
env:
PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }}
HOST: ${{ secrets.EC2_HOST }}
USER: ec2-user
IMAGE: ${{ steps.build-image.outputs.image }}
run: |
echo "$PRIVATE_KEY" > private_key && chmod 400 private_key
ssh -i private_key -o StrictHostKeyChecking=no ${USER}@${HOST} '
docker pull $IMAGE
docker stop my-container || true
docker rm my-container || true
docker run -d --name my-container -p 80:8080 $IMAGE'