DevOps

Automating AWS EC2 Deployments with GitHub Actions CI/CD and Docker Containers

Deploying an application manually is not a big problem when you're working on your first project. You build the application, connect to the server, pull the…

D
DevByteTechnical Author
Published
22 min read9 views
Automating AWS EC2 Deployments with GitHub Actions CI/CD and Docker Containers

Deploying an application manually is not a big problem when you're working on your first project. You build the application, connect to the server, pull the latest code, install dependencies, restart the process, and check whether everything is working.

But what happens when you need to repeat this process every time you push a new feature?

Imagine working on a Node.js API that receives regular updates. Every deployment requires connecting to an EC2 instance, running Git commands, installing packages, restarting the application, and checking the logs. One missed command can cause downtime, and deploying the same application across multiple environments becomes even more difficult.

This is where CI/CD, Docker, and GitHub Actions become useful.

Instead of deploying applications manually, you can create a pipeline that automatically builds a Docker image, pushes it to a container registry, and deploys it to an AWS EC2 instance whenever code is merged into your main branch.

In this guide, we'll build a practical deployment pipeline using Docker, GitHub Actions, Amazon EC2, and Amazon Elastic Container Registry (ECR). We'll also cover AWS permissions, environment variables, deployment failures, and security considerations that matter when running an application in production.

The examples use a Node.js application, but the same deployment approach can be adapted for Python applications built with FastAPI or Flask.

1. Understanding the Deployment Architecture

Before writing the configuration files, let's understand how the components work together.

We'll use the following technologies:

Technology

Purpose

GitHub

Stores application source code

GitHub Actions

Automates testing, building, and deployment

Docker

Packages the application and its dependencies

Amazon ECR

Stores Docker images

Amazon EC2

Runs the application container

AWS IAM

Controls access to AWS resources

GitHub OIDC

Allows GitHub Actions to obtain temporary AWS credentials

The deployment process will look like this:

Developer pushes code
        |
        v
GitHub Repository
        |
        v
GitHub Actions Workflow
        |
        v
Run Tests
        |
        v
Build Docker Image
        |
        v
Authenticate with AWS using OIDC
        |
        v
Push Image to Amazon ECR
        |
        v
Connect to EC2 using SSH
        |
        v
Pull the New Docker Image
        |
        v
Restart the Application Container
        |
        v
Verify Deployment

This architecture separates the application code, container image, and running application.

GitHub stores the source code, ECR stores the built image, and EC2 runs that image.

An important detail is that GitHub Actions builds and publishes the image, while EC2 only needs permission to pull and run it.

We don't need to copy the entire source code to EC2 or install Node.js dependencies manually during every deployment.

2. Prepare the Node.js Application

Let's start with a small Express application.

Create a project directory:

mkdir ec2-docker-deployment
cd ec2-docker-deployment

Initialize the Node.js project:

npm init -y

Install Express:

npm install express

Create an index.js file:

const express = require("express");

const app = express();

const PORT = process.env.PORT || 3000;

app.get("/", (req, res) => {
  res.json({
    message: "Application deployed successfully!",
    environment: process.env.NODE_ENV || "development",
  });
});

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}`);
});

This application has two endpoints.

The root endpoint returns a JSON response confirming that the application is running.

The /health endpoint provides a simple health check that we can use to verify the deployment.

Notice that the application listens on 0.0.0.0, not just 127.0.0.1. This allows the application to accept connections through the container's network interface.

Update the scripts section in package.json:

{
  "scripts": {
    "start": "node index.js",
    "test": "node --test"
  }
}

Keep the other fields generated by npm init and your installed dependencies.

For a real project, your test script should run meaningful automated tests rather than simply exiting successfully. We'll add a basic test shortly.

3. Create a Dockerfile

Docker allows us to package the application into a container image that can run consistently across different environments.

Without Docker, the server may require a particular Node.js version, system packages, and manually installed dependencies.

With Docker, we define the runtime environment in a Dockerfile.

Create a file named Dockerfile:

FROM node:22-alpine

WORKDIR /app

ENV NODE_ENV=production

COPY package*.json ./

RUN npm ci --omit=dev

COPY --chown=node:node . .

USER node

EXPOSE 3000

CMD ["npm", "start"]

Let's understand the important instructions.

Use a specific Node.js runtime

FROM node:22-alpine

This starts from a Node.js image based on Alpine Linux.

For production, choose a supported Node.js version and pin the base image appropriately. For stronger reproducibility, you can pin the image digest and update it through a controlled process.

Set the working directory

WORKDIR /app

All subsequent application commands run inside /app.

Install production dependencies

COPY package*.json ./

RUN npm ci --omit=dev

We copy the package manifests before copying the application source code.

This improves Docker layer caching. If your source code changes but your dependency manifests remain the same, Docker may reuse the dependency-installation layer.

npm ci installs dependencies from the lock file and is designed for reproducible automated builds.

Make sure package-lock.json is committed to your repository.

Run as a non-root user

USER node

Running as a non-root user reduces the impact of some application compromises compared with running the application as root inside the container.

It doesn't eliminate all container security risks, but it's a useful baseline.

Start the application

CMD ["npm", "start"]

This runs the application when Docker starts the container.

Add a .dockerignore file

Create .dockerignore:

node_modules
.git
.github
.env
.env.*
npm-debug.log
coverage

This prevents unnecessary files from being included in the Docker build context.

Be careful with environment files. Secrets should not be copied into the image in the first place. Excluding them from the build context provides an additional safeguard.

For production applications, also consider how you handle build-time secrets, private package credentials, and other sensitive files.

4. Test the Application Locally with Docker

Before configuring AWS, verify that the Docker image builds and the application runs locally.

Build the image:

docker build -t ec2-node-app:local .

Run the container:

docker run -d \
  --name ec2-node-app \
  -p 3000:3000 \
  ec2-node-app:local

Check the root endpoint:

curl http://localhost:3000/

Expected response:

{
  "message": "Application deployed successfully!",
  "environment": "production"
}

Test the health endpoint:

curl http://localhost:3000/health

Expected response:

{
  "status": "healthy"
}

Check the container logs:

docker logs ec2-node-app

If the application works locally, we can move on to the AWS setup.

Stop and remove the local container when you're finished:

docker stop ec2-node-app
docker rm ec2-node-app

Testing the Docker image locally helps catch problems before they reach your EC2 instance.

5. Create an Amazon ECR Repository

Amazon Elastic Container Registry, or ECR, is AWS's managed container image registry.

Instead of storing Docker images directly on your EC2 instance or using a public registry, you can push them to a private ECR repository.

Open the AWS Management Console and navigate to Amazon ECR.

Create a private repository named:

ec2-node-app

Choose your AWS region and keep a note of it. For this guide, we'll use:

ap-south-1

This is the Mumbai region. Use the same region for ECR, the IAM configuration where applicable, and your deployment resources unless you have a specific reason to use different regions.

Your ECR repository URI will look similar to this:

123456789012.dkr.ecr.ap-south-1.amazonaws.com/ec2-node-app

The account number above is illustrative. Replace it with your actual AWS account ID.

You can also create the repository through the AWS CLI:

aws ecr create-repository \
  --repository-name ec2-node-app \
  --region ap-south-1

The identity executing this command needs permission to create ECR repositories.

Why use ECR?

ECR gives you a central place to store container images and integrates with AWS IAM.

This makes it possible to give GitHub Actions permission to push images while giving EC2 permission to pull them.

These permissions should be separate. The EC2 instance doesn't need permission to publish new application images.

6. Launch an EC2 Instance

Next, we need a server to run the container.

Open the EC2 console and launch an instance using a supported Ubuntu Server LTS image.

For a small demonstration, you can start with an instance size suitable for the application's CPU and memory requirements. The right size depends on the workload, traffic, and other services running on the server.

During setup, configure the following:

  • Select an Ubuntu Server LTS AMI.

  • Choose an instance type appropriate for the workload.

  • Create or select an SSH key pair.

  • Attach an appropriate security group.

  • Configure an IAM instance profile.

  • Allocate sufficient storage for the operating system and Docker images.

Configure the security group

Avoid opening every port to the internet.

For SSH access, port 22 should normally be restricted to trusted IP addresses or replaced with a managed access approach such as AWS Systems Manager Session Manager.

If the application listens on port 3000, you have two options:

  1. Temporarily allow port 3000 from your own IP for testing.

  2. In production, keep the application port private and expose the application through Nginx, an Application Load Balancer, or another suitable reverse proxy.

For production, the second approach is generally preferable.

Your public web traffic should normally use HTTPS on port 443. Port 80 may be used to redirect HTTP traffic to HTTPS.

Don't expose SSH or an application port to 0.0.0.0/0 without a clear reason and an appropriate security design.

7. Install Docker on the EC2 Instance

Connect to your EC2 instance using SSH.

For example:

ssh -i your-key.pem ubuntu@YOUR_EC2_PUBLIC_IP

Replace the key filename and public IP with your actual values.

Once connected, update the package index:

sudo apt-get update

Install Docker:

sudo apt-get install -y docker.io

Enable and start the Docker service:

sudo systemctl enable docker
sudo systemctl start docker

Verify the installation:

sudo docker --version

Check that the service is running:

sudo systemctl status docker

For this tutorial, we'll use sudo docker to execute Docker commands. This avoids granting the Ubuntu user additional privileges through Docker group membership.

Membership in the Docker group is highly privileged because Docker can often be used to gain root-level access to the host.

For a production server, consider using Docker's official installation instructions and establish a process for applying security updates to the operating system and Docker engine.

Give EC2 permission to pull from ECR

The EC2 instance needs permission to authenticate with ECR and download images.

Create an IAM role with an EC2 trust relationship, then attach an instance profile containing that role to the instance.

For a simple setup, you can attach the AWS-managed policy:

AmazonEC2ContainerRegistryReadOnly

This allows the instance to read ECR repositories according to the policy's permissions.

For a stricter production setup, create a custom policy scoped to the specific ECR repository and required image-pull actions.

The instance will obtain temporary AWS credentials through its IAM role. You don't need to copy long-lived AWS access keys onto the server.

8. Configure GitHub Actions to Authenticate with AWS

Now we can automate the build and deployment process.

GitHub Actions needs permission to:

  1. Authenticate with AWS.

  2. Push Docker images to ECR.

  3. Connect to EC2 to trigger deployment.

A common mistake is creating an IAM user, generating long-lived access keys, and storing them as GitHub secrets.

That can work, but GitHub Actions can use OpenID Connect (OIDC) to obtain temporary AWS credentials instead.

This avoids storing permanent AWS access keys in GitHub.

Create an OIDC identity provider

In the AWS IAM console, configure an OpenID Connect identity provider for GitHub Actions.

The provider URL is:

https://token.actions.githubusercontent.com

The audience for AWS role assumption is:

sts.amazonaws.com

If your AWS account already has this identity provider configured, you can reuse it.

Create a GitHub Actions IAM role

Create an IAM role with a web identity trust policy that allows the GitHub OIDC provider to assume it.

The trust policy should restrict access to the specific repository and branch that will run the deployment workflow.

For example, replace YOUR_ORG/YOUR_REPO with your actual GitHub repository:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:YOUR_ORG/YOUR_REPO:ref:refs/heads/main"
        }
      }
    }
  ]
}

Replace the example AWS account ID with your own account ID.

The sub condition restricts this role to workflows associated with the specified repository and main branch.

If you use a GitHub environment for deployment, the subject claim may follow an environment-based format instead. Configure the trust policy to match your actual GitHub OIDC claims and deployment strategy.

Add permissions for pushing to ECR

The GitHub Actions role needs permission to upload images to the correct repository.

For a scoped policy, the required permissions typically include:

  • ecr:GetAuthorizationToken on *.

  • ecr:BatchCheckLayerAvailability on the target repository.

  • ecr:InitiateLayerUpload on the target repository.

  • ecr:UploadLayerPart on the target repository.

  • ecr:CompleteLayerUpload on the target repository.

  • ecr:PutImage on the target repository.

The repository-specific actions should be restricted to the ARN of your ec2-node-app ECR repository.

For example:

arn:aws:ecr:ap-south-1:123456789012:repository/ec2-node-app

This follows the principle of least privilege: GitHub Actions can publish the application image without receiving broad administrative access to your AWS account.

9. Store Deployment Configuration in GitHub

Open your GitHub repository.

Navigate to:

Settings → Secrets and variables → Actions

Add the following repository or environment variables:

Name

Purpose

AWS_REGION

AWS region, such as ap-south-1

AWS_ACCOUNT_ID

Your AWS account ID

AWS_ROLE_ARN

ARN of the GitHub Actions IAM role

ECR_REPOSITORY

ec2-node-app

EC2_HOST

Public IP address or DNS name used for SSH

EC2_USER

Usually ubuntu for the Ubuntu AMI used here

EC2_SSH_KEY

Private SSH key used by the deployment workflow

The AWS region, account ID, and repository name aren't inherently secrets, so they can also be configured as GitHub Actions variables.

The IAM role ARN can be stored as a variable if appropriate for your configuration.

The SSH private key must be protected as a secret.

Never commit the private key to the repository or place it inside the Docker image.

Use a dedicated deployment key, restrict its access, and rotate it when necessary. For stronger isolation, consider a private networking arrangement or a managed deployment mechanism instead of SSH.

10. Create the GitHub Actions Workflow

Now comes the main part: automating the build and deployment process.

Create this file in your repository:

.github/workflows/deploy.yml

Add the following workflow:

name: Build and Deploy to EC2

on:
  push:
    branches:
      - main

  workflow_dispatch:

permissions:
  contents: read
  id-token: write

env:
  AWS_REGION: ${{ vars.AWS_REGION }}
  AWS_ACCOUNT_ID: ${{ vars.AWS_ACCOUNT_ID }}
  ECR_REPOSITORY: ${{ vars.ECR_REPOSITORY }}

jobs:
  test:
    name: Run Tests
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "22"
          cache: npm

      - name: Install Dependencies
        run: npm ci

      - name: Run Tests
        run: npm test

  build-and-push:
    name: Build and Push Docker Image
    needs: test
    runs-on: ubuntu-latest

    outputs:
      image_tag: ${{ steps.meta.outputs.image_tag }}

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ vars.AWS_ROLE_ARN }}
          aws-region: ${{ env.AWS_REGION }}

      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v2

      - name: Generate Image Tag
        id: meta
        run: echo "image_tag=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Build and Push Image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: |
            ${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:${{ steps.meta.outputs.image_tag }}
            ${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:latest

  deploy:
    name: Deploy to EC2
    needs: build-and-push
    runs-on: ubuntu-latest

    steps:
      - name: Deploy Application
        env:
          EC2_HOST: ${{ secrets.EC2_HOST }}
          EC2_USER: ${{ vars.EC2_USER }}
          EC2_SSH_KEY: ${{ secrets.EC2_SSH_KEY }}
          IMAGE_TAG: ${{ needs.build-and-push.outputs.image_tag }}
        run: |
          set -euo pipefail

          mkdir -p ~/.ssh
          chmod 700 ~/.ssh

          printf '%s\n' "$EC2_SSH_KEY" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key

          ssh-keyscan -H "$EC2_HOST" >> ~/.ssh/known_hosts

          ssh \
            -i ~/.ssh/deploy_key \
            -o StrictHostKeyChecking=yes \
            "$EC2_USER@$EC2_HOST" \
            "AWS_REGION='$AWS_REGION' \
             AWS_ACCOUNT_ID='$AWS_ACCOUNT_ID' \
             ECR_REPOSITORY='$ECR_REPOSITORY' \
             IMAGE_TAG='$IMAGE_TAG' \
             bash -s" <<'REMOTE_SCRIPT'
          set -euo pipefail

          IMAGE_URI="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPOSITORY}:${IMAGE_TAG}"

          aws ecr get-login-password --region "$AWS_REGION" \
            | sudo docker login \
                --username AWS \
                --password-stdin \
                "${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"

          sudo docker pull "$IMAGE_URI"

          if sudo docker inspect node-app >/dev/null 2>&1; then
            sudo docker stop node-app
            sudo docker rm node-app
          fi

          sudo docker run -d \
            --name node-app \
            --restart unless-stopped \
            -p 3000:3000 \
            "$IMAGE_URI"

          for attempt in $(seq 1 20); do
            if curl --fail --silent \
              http://127.0.0.1:3000/health >/dev/null; then
              echo "Deployment health check passed"
              exit 0
            fi

            sleep 3
          done

          echo "Health check failed"
          sudo docker logs --tail 100 node-app
          exit 1
          REMOTE_SCRIPT

Before using this workflow, review the action versions and pin third-party actions to verified full commit SHAs according to your organization's supply-chain security policy. The version tags above make the example easier to read, but mutable tags are not the strongest option for a security-sensitive production pipeline.

Also, the workflow assumes that the runner's SSH host-key verification process has been established securely. The ssh-keyscan command collects a host key but does not independently prove the host's identity. For a hardened deployment, verify the EC2 SSH host key through a trusted channel and maintain a trusted known_hosts entry.

Let's understand the workflow step by step.

Step 1: Trigger the workflow

on:
  push:
    branches:
      - main

Whenever code is pushed to main, the workflow starts automatically.

The workflow_dispatch event also allows you to start a deployment manually from the GitHub Actions interface.

For production, you may prefer to trigger deployment only after a pull request has been reviewed and merged.

Step 2: Run tests

test:
  ...

The pipeline checks out the repository, installs Node.js, runs npm ci, and executes the test script.

The build-and-push job depends on this job:

needs: test

If the tests fail, the workflow won't proceed to the image-publishing stage.

For a real application, include meaningful unit tests, integration tests, and security checks as appropriate.

Step 3: Authenticate with AWS using OIDC

- name: Configure AWS Credentials
  uses: aws-actions/configure-aws-credentials@v4
  with:
    role-to-assume: ${{ vars.AWS_ROLE_ARN }}
    aws-region: ${{ env.AWS_REGION }}

This exchanges the GitHub OIDC identity for temporary AWS credentials.

The workflow needs:

permissions:
  contents: read
  id-token: write

id-token: write allows GitHub Actions to request an OIDC token.

The IAM trust policy determines whether that identity can assume the role.

Step 4: Build and push the Docker image

The workflow tags the image with the Git commit SHA:

ec2-node-app:<commit-sha>

It also updates the latest tag.

Using a commit-specific tag is important because it allows you to identify exactly which source revision produced an image.

For production deployments, use the immutable commit-specific tag or image digest rather than relying on latest.

The latest tag is convenient for humans, but it can change whenever another image is published.

Step 5: Connect to EC2 and deploy

The final job connects to the EC2 instance using SSH.

The EC2 instance authenticates to ECR using its attached IAM role:

aws ecr get-login-password --region "$AWS_REGION"

The workflow then pulls the exact image associated with the current Git commit and starts a new container.

The container is named node-app, and Docker is configured to restart it automatically if the process exits or the Docker service restarts.

An important limitation of this deployment method

The example stops and removes the existing container before starting the new one.

This is simple, but it introduces a period of downtime during deployment. If the new container fails to start, the previous container has already been removed.

We'll discuss how to improve this in the production considerations below.

11. Add a Basic Automated Test

Our workflow runs:

npm test

Let's add a small test so the pipeline has something meaningful to execute.

Create a file named app.test.js:

const test = require("node:test");
const assert = require("node:assert/strict");

test("health endpoint returns healthy status", async () => {
  const response = await fetch(
    "http://127.0.0.1:3000/health"
  );

  assert.equal(response.status, 200);

  const body = await response.json();

  assert.equal(body.status, "healthy");
});

This test expects the application to already be running.

For a complete CI setup, a better approach is to separate the Express application from the listener so tests can start the application programmatically without depending on a manually running server.

For example, you can export an Express app from an app.js module and start the listener from a separate server.js file. Your tests can then use an HTTP testing library or a temporary local server.

The important point is that the tests should be self-contained and repeatable. They should not depend on a developer having manually started a service on the CI runner.

Before deploying, verify that npm test succeeds on a clean checkout.

12. Configure the EC2 Instance for Secure Image Pulls

Our deployment script uses:

aws ecr get-login-password

This requires the AWS CLI to be installed on EC2 and the instance role to have the required ECR permissions.

Check whether the AWS CLI is available:

aws --version

If it isn't installed, install a supported AWS CLI version using the official AWS installation instructions for Ubuntu.

Then verify that the instance can obtain its role credentials and authenticate with ECR.

The EC2 role needs only the permissions required to pull images from the target repository.

Do not put permanent AWS access keys in the deployment script or Docker image.

Why separate the permissions?

There are two different responsibilities in this architecture:

GitHub Actions: Builds and pushes new images.

EC2: Pulls images and runs containers.

If the EC2 instance is compromised, a read-only ECR role limits the attacker's ability to publish a malicious image into the repository.

Likewise, the GitHub Actions role should not receive unnecessary EC2 administrative permissions.

Separating these responsibilities makes the deployment pipeline easier to audit and reduces the potential impact of compromised credentials.

13. Deploy Without Losing the Previous Image

The initial deployment script is intentionally simple, but production deployments need a better failure strategy.

Consider this sequence:

  1. The new image is pulled successfully.

  2. The existing container is stopped.

  3. The existing container is removed.

  4. The new container starts.

  5. The new container crashes because of a configuration error.

At this point, the application is unavailable.

A safer single-instance deployment can retain the previous image and restart it if the new deployment fails.

For example, before replacing the existing container, record the current image reference:

OLD_IMAGE=""

if sudo docker inspect node-app >/dev/null 2>&1; then
  OLD_IMAGE=$(sudo docker inspect \
    --format='{{.Config.Image}}' node-app)
fi

Pull the new image before stopping the old container:

sudo docker pull "$IMAGE_URI"

Then stop and remove the old container, start the new one, and perform the health check.

If the health check fails, remove the failed container and start the old image again:

if [ -n "$OLD_IMAGE" ]; then
  sudo docker run -d \
    --name node-app \
    --restart unless-stopped \
    -p 3000:3000 \
    "$OLD_IMAGE"
fi

This is only the rollback portion of the process; a complete deployment script must also handle the new container's failure, name conflicts, logging, and cleanup.

Even with rollback, there can be downtime between stopping the old container and successfully starting the replacement.

For applications where availability matters, consider a blue-green deployment, a load balancer with multiple targets, or an orchestrator that supports rolling updates and health-based traffic management.

14. Handling Environment Variables and Secrets

Most applications require configuration that shouldn't be included in the Docker image.

For example:

DATABASE_URL
JWT_SECRET
REDIS_URL
NODE_ENV

Don't place production secrets directly in your Dockerfile:

ENV JWT_SECRET=my-secret-key

That can expose secrets through image layers or image metadata.

Instead, supply configuration at runtime using a secure configuration mechanism.

For AWS-hosted applications, common options include:

  • AWS Secrets Manager.

  • AWS Systems Manager Parameter Store.

  • Protected environment configuration managed by your deployment process.

For a small demonstration, you could use a protected environment file stored on EC2 and pass it to Docker using --env-file.

However, that file must have appropriate ownership and permissions, must not be committed to Git, and must be managed as a secret.

For production, consider retrieving secrets from a managed service through the EC2 instance role. Restrict that role to the exact secrets the application needs, and define how secrets are rotated.

Avoid passing sensitive values as command-line arguments where they may be exposed through process listings, logs, or debugging output.

15. Common Deployment Problems and How to Fix Them

Even when the pipeline is configured correctly, deployment problems can still happen.

Here are some common examples.

Problem 1: GitHub Actions cannot assume the AWS role

You may see an error related to AssumeRoleWithWebIdentity.

Check the following:

  • The GitHub OIDC provider exists in IAM.

  • The audience matches sts.amazonaws.com.

  • The role trust policy matches the actual repository and branch.

  • The workflow includes id-token: write.

  • The role ARN and AWS region are configured correctly.

A mismatch in the OIDC subject claim is a common cause of failure.

Problem 2: Docker cannot pull the ECR image

If the EC2 instance cannot pull the image, check:

  • The instance has an IAM role attached.

  • The role has permission to pull from the repository.

  • The repository exists in the configured region.

  • The account ID and image URI are correct.

  • The instance can reach the ECR API and registry endpoints.

For private subnets, network connectivity is especially important. Depending on the architecture, the instance may need NAT access or suitable VPC endpoints for ECR and Amazon S3, which ECR uses for image layers.

Problem 3: The application starts but the endpoint is unavailable

Check the container:

sudo docker ps

Inspect the logs:

sudo docker logs node-app

Check whether the application is listening on the expected port and whether the Docker port mapping is correct.

Also verify the EC2 security group, host firewall, and any reverse-proxy configuration.

Remember that a Docker health check against 127.0.0.1:3000 on the EC2 host verifies local access. It doesn't prove that the application is reachable from the internet or that your HTTPS endpoint is configured correctly.

Problem 4: The application fails after deployment

A new image might have missing environment variables, an incompatible database schema, or a broken application dependency.

Check the logs and health endpoint, then roll back to the previous known-good image if necessary.

For database changes, use backward-compatible migration strategies whenever possible. Rolling back the application container doesn't automatically roll back database schema changes or data modifications.

16. Production Improvements Worth Considering

The pipeline we've built is a useful starting point, but a production deployment should include additional controls.

Area

Improvement

CI/CD security

Pin third-party GitHub Actions to verified commit SHAs

AWS permissions

Use OIDC and narrowly scoped IAM roles

Image management

Deploy immutable image tags or digests

Container security

Run as non-root and scan images for vulnerabilities

Network security

Keep internal application ports private

HTTPS

Use Nginx, an Application Load Balancer, or another suitable TLS termination layer

Availability

Use health checks and an appropriate rollback or rolling-deployment strategy

Secrets

Retrieve sensitive configuration from a managed secrets service

Testing

Add unit, integration, and security tests

Monitoring

Collect logs, metrics, and application health information

Dependency management

Keep lock files and scan for vulnerable dependencies

Operations

Establish backup, recovery, and incident-response procedures

Consider deployment concurrency

Another useful improvement is preventing two deployment workflows from replacing each other's containers simultaneously.

GitHub Actions supports concurrency controls that can help serialize deployments to a shared environment.

For example:

concurrency:
  group: production-deployment
  cancel-in-progress: false

Place this at the workflow level if you want production deployments to share a concurrency group.

The exact strategy depends on whether you want pending deployments to wait, whether older deployments should be skipped, and how your release process handles concurrent commits.

Use separate environments

For a larger project, consider maintaining separate development, staging, and production environments.

Each environment should have its own configuration, permissions, and deployment rules.

For example, changes might deploy automatically to staging after tests pass, while production deployment requires approval.

GitHub Environments can provide deployment protection rules and environment-specific secrets and variables where supported by your repository and plan.

Conclusion

Automating AWS EC2 deployments with GitHub Actions and Docker can remove a large amount of repetitive work from your development process.

Instead of manually connecting to the server, pulling source code, installing dependencies, and restarting the application, you can build a repeatable pipeline that tests the code, creates a Docker image, pushes it to Amazon ECR, and deploys it to EC2.

In this guide, we built a simple Express application, created a Docker image, configured ECR, prepared an EC2 instance, and connected GitHub Actions to AWS using OIDC.

We also explored deployment rollback, environment secrets, IAM permissions, health checks, and common problems that occur when deploying containerized applications.

The most important takeaway is that automating deployment is only part of the job; the pipeline must also be secure, repeatable, and able to recover from failures.

Start with a small workflow, verify that each stage works, and improve it as your application grows. Add meaningful tests, restrict permissions, protect secrets, scan your images, and introduce a deployment strategy that matches your availability requirements.

Once these foundations are in place, you can apply the same approach to Python applications built with FastAPI or Flask, as well as more complex backend services.

A well-designed CI/CD pipeline doesn't just save time. It makes releases more consistent, reduces manual errors, and gives your team a clearer path from writing code to running it reliably in production.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘