Merge pull request #171 from lass9436/lass9436 #2
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: Build and Deploy Docker Image | |
on: | |
push: | |
branches: | |
- lass9436 | |
jobs: | |
build_and_deploy: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout code | |
uses: actions/checkout@v2 | |
- name: Set up Docker Buildx | |
uses: docker/setup-buildx-action@v2 | |
- name: Build Docker image | |
run: docker build -t jsp-cafe:latest . | |
- name: Save Docker image to file | |
run: docker save jsp-cafe:latest | gzip > jsp-cafe.tar.gz | |
- name: Upload Docker image file | |
uses: actions/upload-artifact@v3 | |
with: | |
name: docker-image | |
path: jsp-cafe.tar.gz | |
- name: Setup known hosts | |
run: | | |
mkdir -p ~/.ssh | |
echo "${{ secrets.EC2_HOST_KEY }}" >> ~/.ssh/known_hosts | |
chmod 644 ~/.ssh/known_hosts | |
- name: Deploy to EC2 | |
env: | |
SSH_PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }} | |
EC2_USER: ${{ secrets.EC2_USER }} | |
EC2_HOST: ${{ secrets.EC2_HOST }} | |
run: | | |
# Save the SSH private key to a file | |
echo "$SSH_PRIVATE_KEY" > private_key.pem | |
chmod 600 private_key.pem | |
# Transfer the Docker image file to EC2 server | |
scp -i private_key.pem jsp-cafe.tar.gz $EC2_USER@$EC2_HOST:/tmp/ | |
# Connect to EC2 server and run Docker commands | |
ssh -i private_key.pem $EC2_USER@$EC2_HOST << 'EOF' | |
docker load < /tmp/jsp-cafe.tar.gz | |
docker stop jsp-cafe || true | |
docker rm jsp-cafe || true | |
docker run -d -p 8080:8080 --add-host=host.docker.internal:host-gateway --name jsp-cafe jsp-cafe:latest | |
EOF |