Automating Docker Deployments on AWS EC2 Using GitHub Actions: A Complete CI/CD Guide
Learn how to build an automated CI/CD pipeline using GitHub Actions, Docker, GitHub Container Registry, and AWS EC2. This step-by-step guide covers containerization, workflow configuration, automated deployments, application updates, security considerations, and troubleshooting.
Automating Docker Deployments on AWS EC2 Using GitHub Actions: A Complete CI/CD Guide
Introduction
Imagine developing a Node.js application, pushing your latest code to GitHub, and watching it automatically deploy to your AWS EC2 server without manually connecting to the machine every time.
This is exactly what a Continuous Integration and Continuous Deployment (CI/CD) pipeline can help us achieve.
When I first started exploring Docker deployments on Amazon EC2, I realized that containerizing an application was only one part of the process. Updating it still required multiple manual steps: connecting through SSH, pulling code, building an image, stopping the old container, and starting a new one.
These steps are manageable for small projects, but repeating them every time we modify the application becomes inefficient.
In this article, we will automate that process using GitHub Actions, Docker, GitHub Container Registry (GHCR), and Amazon EC2.
Our objective is simple:
Push code to GitHub → Build Docker image → Push image to registry → Deploy automatically on EC2.
Let's explore how this works.
1. What Is CI/CD?
CI/CD stands for Continuous Integration and Continuous Delivery or Deployment.
Continuous Integration (CI)
Continuous Integration involves automatically building and testing application changes whenever developers push code to a shared repository.
For example, when a developer pushes a Node.js application to GitHub, a workflow can automatically:
- Retrieve the latest source code.
- Install dependencies.
- Run automated tests.
- Build a Docker image.
- Publish the image to a container registry.
This helps identify problems before releasing updates.
Continuous Deployment (CD)
Continuous Deployment takes automation further by releasing validated application changes to the target environment without requiring manual intervention.
In our project, GitHub Actions will establish an SSH connection to EC2 and deploy the latest Docker image after the build succeeds.
The major benefit is that developers can spend more time building applications and less time repeating deployment commands.
2. Understanding Our CI/CD Architecture
Our deployment architecture follows this flow:
Developer | | git push origin main vGitHub Repository | vGitHub Actions | +--> Run Tests | +--> Build Docker Image | +--> Push Image to GHCR | vAWS EC2 Instance | +--> Pull Latest Image | +--> Stop Old Container | +--> Start New Container | vUpdated Node.js ApplicationTechnologies Used
Technology | Purpose |
|---|---|
GitHub | Source code management |
GitHub Actions | CI/CD automation |
Docker | Application containerization |
GHCR | Docker image storage |
AWS EC2 | Application hosting |
SSH | Remote deployment |
Node.js | Example backend application |
For simplicity, we will use a publicly accessible GHCR container image. For private applications, authenticated image pulls and stricter access controls are recommended.
3. Prerequisites
Before beginning, we need:
- An AWS account.
- An EC2 instance running Amazon Linux 2023.
- Docker installed on EC2.
- A GitHub repository containing a Node.js application.
- An SSH key configured for secure access.
- Basic understanding of Git, Docker, and Linux commands.
Note: AWS resources can incur charges. Check EC2 pricing, storage, and data-transfer costs before starting.
4. Create a Node.js Application
Let's start with a basic Express application.
Create a project directory:
mkdir nodejs-cicd-democd nodejs-cicd-demoInitialize Node.js and install Express:
npm init -ynpm install expressCreate a file named
server.js :const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
app.get("/", (req, res) => { res.json({ message: "Application deployed using GitHub Actions!", status: "success", environment: "AWS EC2" });});
app.get("/health", (req, res) => { res.status(200).json({ status: "healthy" });});
app.listen(PORT, "0.0.0.0", () => { console.log(`Server running on port ${PORT}`);});In
package.json , configure the start script:"scripts": { "start": "node server.js"}Run the application locally:
npm startVisit:
http://localhost:3000The application should display a JSON response.
Our backend is now ready to be containerized.
5. Create a Dockerfile
A Dockerfile contains the instructions needed to package an application into a Docker image.
Create a file named
Dockerfile :FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
EXPOSE 3000
USER node
CMD ["npm", "start"]Understanding the Dockerfile
FROM: Specifies the base Node.js image.
WORKDIR: Defines the application directory inside the container.
COPY: Copies required project files.
RUN: Installs production dependencies using the lockfile.
EXPOSE: Documents the port used by the application.
USER: Runs the application as a non-root user.
CMD: Starts the Node.js application.
Make sure the project includes the
package-lock.json file generated during dependency installation, because npm ci requires it.Create a
.dockerignore file:node_modules.git.github.env*.pemnpm-debug.logThis prevents unnecessary files and local secrets from being included in the Docker build context.
6. Test Docker Locally
Before automating anything, verify that the image builds successfully.
Build the image:
docker build -t nodejs-cicd-demo .Run a container:
docker run -d \ --name nodejs-test \ -p 3000:3000 \ nodejs-cicd-demoCheck running containers:
docker psTest the health endpoint:
curl http://localhost:3000/healthExpected response:
{ "status": "healthy"}After testing, remove the container:
docker rm -f nodejs-testTesting the image locally helps catch errors before deploying it to the cloud.
7. Launch and Configure AWS EC2
Open the AWS Management Console and navigate to EC2.
Launch an instance with the following configuration:
Setting | Configuration |
|---|---|
AMI | Amazon Linux 2023 |
Instance type | Based on workload |
Key pair | Existing or new key |
HTTP | Port 80 |
SSH | Port 22, restricted access |
For this example, choose an EC2 instance with a public IPv4 address and internet connectivity.
Configure its security group to allow:
- HTTP traffic on port 80 from users who need access.
- SSH traffic on port 22 only from approved source IP addresses.
Security consideration: GitHub-hosted runners may use changing IP ranges. Do not broadly expose SSH simply to make automated deployment work. For a demonstration, use a properly restricted deployment endpoint or trusted runner. For production, consider a self-hosted runner, AWS Systems Manager, or another deployment method that avoids opening SSH to arbitrary internet sources.
Connect to EC2
Use your private key to connect:
chmod 400 my-key.pemssh -i my-key.pem \ ec2-user@YOUR_EC2_PUBLIC_IPReplace the placeholders with your actual instance information.
8. Install Docker on EC2
Update the operating system:
sudo dnf update -yInstall Docker:
sudo dnf install -y dockerStart and enable Docker:
sudo systemctl enable --now dockerVerify the installation:
sudo docker --versionFor this tutorial, we will execute Docker commands using
sudo rather than adding the deployment user to the Docker group.Docker administration provides powerful host-level access, so deployment credentials must be carefully protected.
9. Understanding GitHub Container Registry
GitHub Container Registry stores Docker images at:
ghcr.ioInstead of rebuilding the application on EC2, our pipeline will build it using GitHub Actions and push it to GHCR.
For example:
ghcr.io/username/nodejs-cicd-demoThe EC2 instance will download the image from the registry whenever a new deployment is triggered.
Why Use a Container Registry?
A container registry provides:
- Centralized image storage.
- Consistent deployment artifacts.
- Version-based image tagging.
- Easier reuse of images across servers.
- Separation between image building and deployment.
In this tutorial, we use immutable commit-based image tags so each deployment can be associated with a particular version of the source code.
10. Configure GitHub Repository Secrets
GitHub Actions needs secure access to our EC2 server.
Open the GitHub repository and navigate to:
Settings → Secrets and variables → Actions
Create the following repository secrets:
Secret | Description |
|---|---|
EC2_HOST | EC2 public IP or DNS name |
EC2_USER | SSH username |
EC2_SSH_KEY | Private key for a dedicated deployment identity |
EC2_KNOWN_HOSTS | Verified SSH host key entry |
Use a dedicated deployment SSH key, install its public key on EC2, and restrict who can access or modify these secrets.
Do not upload your private SSH key into the repository itself.
The
EC2_KNOWN_HOSTS value should be generated from the server's SSH host key and verified using a trusted source. You can use ssh-keyscan to retrieve a candidate entry, but verify the fingerprint independently before trusting it.This is important because skipping SSH host verification can expose the deployment process to man-in-the-middle attacks.
For the example below, set the GHCR package visibility to public after its first publication. Public visibility allows EC2 to pull it without storing registry credentials. Do not publish private application images this way.
11. Create the GitHub Actions Workflow
Now we reach the main part of our project.
Inside the repository, create this directory:
.github/workflows/Inside it, create:
deploy.ymlAdd the following workflow:
name: Docker CI/CD to AWS EC2
on: push: branches: - main
workflow_dispatch:
permissions: contents: read packages: write
concurrency: group: ec2-production cancel-in-progress: false
jobs: build-and-deploy: runs-on: ubuntu-latest
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Setup Docker Buildx uses: docker/setup-buildx-action@v3
- name: Prepare Image Name id: image run: | IMAGE=$(echo \ "ghcr.io/${GITHUB_REPOSITORY}" \ | tr '[:upper:]' '[:lower:]')
echo "name=$IMAGE" >> "$GITHUB_OUTPUT"
- name: Login to GHCR uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and Push Image uses: docker/build-push-action@v6 with: context: . push: true tags: | ${{ steps.image.outputs.name }}:${{ github.sha }}
- name: Configure SSH env: SSH_KEY: ${{ secrets.EC2_SSH_KEY }} KNOWN_HOSTS: ${{ secrets.EC2_KNOWN_HOSTS }} run: | mkdir -p ~/.ssh chmod 700 ~/.ssh
printf '%s\n' "$SSH_KEY" > ~/.ssh/id_ed25519 printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts
chmod 600 ~/.ssh/id_ed25519 chmod 600 ~/.ssh/known_hosts
- name: Deploy to EC2 env: HOST: ${{ secrets.EC2_HOST }} USER: ${{ secrets.EC2_USER }} IMAGE: ${{ steps.image.outputs.name }}:${{ github.sha }} run: | ssh -o BatchMode=yes "$USER@$HOST" \ "bash -s -- '$IMAGE'" <<'REMOTE' set -euo pipefail
IMAGE="$1"
sudo docker pull "$IMAGE"
sudo docker rm -f nodejs-app || true
sudo docker run -d \ --name nodejs-app \ --restart unless-stopped \ -p 80:3000 \ "$IMAGE"
for i in $(seq 1 15); do if curl -fsS http://localhost/health; then echo "Deployment successful" exit 0 fi
sleep 2 done
sudo docker logs nodejs-app exit 1 REMOTEImportant Workflow Notes
This workflow assumes:
- The default branch is named
main.
- Your EC2 server runs Docker.
- The SSH key is stored in the GitHub secret in a format supported by SSH.
- The SSH host is reachable from the selected runner.
- The GHCR package is public before the deployment step.
- The instance architecture is compatible with the image built by GitHub Actions.
- The application provides a working
/healthendpoint.
For a production implementation, pin third-party actions to reviewed commit SHAs, use protected deployment environments, and consider authenticated private container images.
The example demonstrates automated deployment but does not provide zero-downtime release management.
12. Understanding the Workflow Step by Step
Step 1: Detect Code Changes
The workflow starts automatically whenever code is pushed to the
main branch.on: push: branches: - mainThis allows developers to trigger a deployment through a normal Git push.
The
workflow_dispatch event also enables manual execution from the GitHub Actions interface.Step 2: Retrieve Source Code
The checkout action downloads the application repository into the GitHub Actions runner.
Step 3: Prepare Docker
Docker Buildx prepares the build environment used to create the application image.
Step 4: Authenticate to GHCR
GitHub Actions authenticates using its temporary
GITHUB_TOKEN , with package write permission.This avoids storing a long-lived personal access token just to publish images from the workflow.
Step 5: Build and Push the Image
The pipeline builds the container image and publishes it to GHCR.
Each image is tagged with the Git commit SHA, allowing us to identify the exact source revision associated with the deployment.
Step 6: Connect to EC2
The workflow establishes an authenticated SSH connection using the configured secrets.
SSH host verification protects the connection from untrusted server impersonation.
Step 7: Deploy the New Container
EC2 performs the following operations:
- Downloads the new Docker image.
- Removes the existing application container.
- Creates a new container using the updated image.
- Tests the application's health endpoint.
If the health check fails, the workflow reports deployment failure.
This process is intentionally simple and may cause a brief interruption while replacing the application. Production systems should consider safer rollout and recovery mechanisms.
13. Push Code to Trigger the Pipeline
Now that the workflow is configured, push your project to GitHub.
git add .git commit -m "Add automated Docker deployment"git push origin mainNavigate to:
GitHub Repository → Actions
You should see the new workflow run.
Open the run to inspect:
- Source checkout
- Docker image build
- GHCR image publication
- EC2 deployment
- Application health verification
If a step fails, the workflow logs will help identify the issue.
For the first run, the package may initially be private. Set the GHCR package to public before expecting unauthenticated image pulls on EC2, or replace this approach with authenticated pulls.
14. Verify the Deployment on EC2
After the workflow completes successfully, connect to EC2 and verify the container:
sudo docker psView logs:
sudo docker logs nodejs-appTest the local application:
curl http://localhost/healthThen open the application from your browser:
http://YOUR_EC2_PUBLIC_IPYou should receive a response similar to:
{ "message": "Application deployed using GitHub Actions!", "status": "success", "environment": "AWS EC2"}This is the expected result of the example. The response will appear only after the workflow is configured and deployment succeeds.
15. Test an Automatic Application Update
Let's modify the response in our Node.js application.
Change the message to:
message: "Updated automatically using CI/CD!"Commit and push:
git add .git commit -m "Update application response"git push origin mainGitHub Actions will trigger another deployment.
The pipeline builds a new image and replaces the running EC2 container.
After successful deployment, refresh the application in your browser to verify the updated response.
This demonstrates the main advantage of CI/CD: a repeatable deployment process requiring fewer manual steps.
16. Troubleshooting Common CI/CD Errors
Error: Permission Denied (Publickey)
The workflow cannot authenticate to the EC2 server.
Check the SSH username, deployment key, authorized public key, and GitHub repository secrets.
Error: Docker Pull Access Denied
Possible reasons include:
- The GHCR package is private.
- The image name is incorrect.
- The image tag does not exist.
- Container registry authentication is missing.
Verify the published image and its visibility.
Error: Connection Timed Out
The GitHub runner may be unable to reach EC2.
Check the instance's public connectivity, security group, network ACLs, routing, and SSH access policy.
Do not disable network restrictions simply to bypass the problem.
Error: Container Is Running but Website Is Unavailable
Verify the application port:
sudo docker psInspect logs:
sudo docker logs nodejs-appCheck the health endpoint:
curl http://localhost/healthConfirm port 80 is reachable and the application listens on
0.0.0.0 inside the container.Error: Health Check Failed
The container may have started but the application is not ready or has crashed.
Inspect the application logs and verify that the health endpoint returns HTTP 200.
17. Future Improvements
The workflow presented here is a useful starting point, but there are several improvements we can make.
Automated Testing
Add unit tests and integration tests before building the Docker image.
A failed test should prevent deployment.
Amazon ECR Integration
GitHub Container Registry works for this example, but Amazon Elastic Container Registry is another option for storing images within the AWS ecosystem.
For ECR, GitHub Actions can use OpenID Connect (OIDC) to obtain short-lived AWS credentials without storing long-lived AWS access keys.
Monitoring With Prometheus and Grafana
Monitor application performance, container resource usage, and service availability.
Prometheus can collect metrics while Grafana provides dashboards for visualization.
CloudWatch Logs and Alerts
Amazon CloudWatch can provide centralized logging and alerting for applications running on AWS.
Rollback Support
Retain previous image tags so that an earlier release can be redeployed if the latest version fails.
A robust system should validate a new release before removing the old, healthy version.
HTTPS and Load Balancing
For real production applications, configure HTTPS using an appropriate reverse proxy or AWS Application Load Balancer.
Approval-Based Deployments
Use GitHub environments, required reviewers, and branch protection rules so only approved changes reach production.
These improvements can help turn a basic automated deployment into a more reliable delivery platform.
18. What I Learned From This Workflow
The most valuable lesson from building CI/CD pipelines is that DevOps is not simply about learning individual tools.
It is about understanding how those tools work together.
GitHub manages the source code, GitHub Actions automates the workflow, Docker produces a portable deployment artifact, and AWS EC2 provides the infrastructure to run the application.
Connecting these technologies reduces repetitive operational work and makes deployment behavior more consistent.
At the same time, automation introduces responsibility. SSH credentials, image access, network security, deployment failures, and recovery processes must be designed carefully.
A good CI/CD pipeline should not only deploy quickly. It should also be secure, observable, repeatable, and recoverable.
Conclusion
In this tutorial, we explored how to automate Docker-based application deployment on Amazon EC2 using GitHub Actions.
We learned how to:
- Containerize a Node.js application.
- Configure an Amazon EC2 server.
- Publish images to GitHub Container Registry.
- Create GitHub Actions workflows.
- Deploy application updates automatically.
- Verify deployment health.
- Troubleshoot common CI/CD problems.
This workflow provides a practical foundation for learning cloud-based DevOps automation.
The next step is to enhance the pipeline with automated testing, secure cloud authentication, image scanning, monitoring, and zero-downtime deployment strategies.
What tools are you currently using for CI/CD: GitHub Actions, Jenkins, GitLab CI, or AWS CodePipeline? Share your experience in the comments!
References
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article