Artificial Intelligence

How to Deploy an AI Application Using Docker and AWS

Building an AI application locally is only the first step. To make it available to real users, you need to deploy it to a server, configure its environment,…

D
DevByteTechnical Author
Published
18 min read3 views
How to Deploy an AI Application Using Docker and AWS

Building an AI application locally is only the first step. To make it available to real users, you need to deploy it to a server, configure its environment, manage dependencies, and ensure that it can handle requests reliably.

For example, imagine you've built an AI chatbot using Node.js, an LLM API, and a vector database. The application works perfectly on your laptop, but now you want to deploy it so users can access it through your website.

This is where Docker and AWS become useful.

Docker packages your application and its dependencies into a container, making it easier to run consistently across development and production environments. AWS provides cloud infrastructure and services that allow you to run, secure, monitor, and scale your application.

In this guide, you'll learn how to containerize an AI application using Docker and deploy it to AWS using Amazon ECS with AWS Fargate.

We'll cover:

  • Understanding Docker and AWS.

  • Creating a Node.js AI API.

  • Writing a production-ready Dockerfile.

  • Building and testing the Docker image.

  • Pushing the image to Amazon ECR.

  • Deploying the application using Amazon ECS and Fargate.

  • Configuring environment variables and security.

  • Monitoring and scaling the application.

By the end, you'll understand the main steps involved in deploying an AI application to the cloud.

1. Understanding Docker and AWS

Before starting the deployment, let's understand the technologies involved.

What Is Docker?

Docker is a platform for packaging applications into containers.

A container includes your application code, runtime, dependencies, and the configuration required to run the application.

For example, a Node.js AI application might require:

  • Node.js.

  • Express.js.

  • LangChain.

  • OpenAI SDK.

  • Environment configuration.

  • Application source code.

Without containers, differences between local and production environments can cause dependency and configuration problems.

Docker helps reduce these inconsistencies by packaging the application into a reusable image.

Learn more from the official Docker Documentation.

What Is AWS?

Amazon Web Services (AWS) provides cloud infrastructure and managed services for hosting applications.

For our deployment, we'll use the following AWS services:

AWS Service

Purpose

Amazon ECR

Stores Docker images

Amazon ECS

Runs and manages containers

AWS Fargate

Runs containers without requiring you to manage EC2 servers

Application Load Balancer

Routes incoming HTTP or HTTPS requests

AWS IAM

Controls access to AWS resources

AWS Secrets Manager

Stores sensitive credentials

Amazon CloudWatch

Collects logs and monitoring data

These services work together to provide a container-based deployment architecture.

2. Deployment Architecture

Our application will follow this architecture:

                 Users
                   |
                   v
             HTTPS Request
                   |
                   v
        Application Load Balancer
                   |
                   v
             Amazon ECS
                   |
                   v
             AWS Fargate
                   |
                   v
          Node.js AI Application
                   |
             +-----+------+
             |            |
             v            v
         LLM API     Vector Database

The Docker image will be stored in Amazon ECR.

Amazon ECS will use that image to start containers on AWS Fargate. An Application Load Balancer can distribute incoming requests across healthy application tasks.

The AI application can then communicate with an external LLM provider and a vector database.

Important: The LLM API and vector database are separate dependencies. You must configure their credentials, network access, and availability independently of the container deployment.

For the tutorial, we'll deploy the Node.js API first. You can connect a vector database or other AI services afterward.

3. Create a Node.js AI Application

Let's build a simple AI API using Node.js, Express.js, and the OpenAI SDK.

If you already have an AI application, you can use your existing project instead and adapt the Docker configuration.

Step 1: Create the Project

Run the following commands:

mkdir ai-docker-aws
cd ai-docker-aws

npm init -y

Install the dependencies:

npm install express openai dotenv

Install development dependencies:

npm install -D typescript tsx @types/node @types/express

Initialize TypeScript:

npx tsc --init

Create the following structure:

ai-docker-aws/
├── src/
│   └── index.ts
├── .env
├── .dockerignore
├── Dockerfile
├── package.json
├── package-lock.json
└── tsconfig.json

Step 2: Configure the Environment

Create a .env file:

OPENAI_API_KEY=your_openai_api_key
PORT=3000

Replace the placeholder with your actual API key.

Never commit .env files containing secrets to Git or include them in a Docker image.

Step 3: Build the AI API

Create src/index.ts:

import "dotenv/config";

import express from "express";
import OpenAI from "openai";

const app = express();

app.use(express.json());

const port = Number(process.env.PORT || 3000);

const apiKey = process.env.OPENAI_API_KEY;

if (!apiKey) {
  throw new Error("OPENAI_API_KEY is required");
}

const openai = new OpenAI({
  apiKey,
});

app.get("/health", (_req, res) => {
  res.status(200).json({
    status: "ok",
  });
});

app.post("/api/ai", async (req, res) => {
  try {
    const { message } = req.body;

    if (
      typeof message !== "string" ||
      !message.trim()
    ) {
      return res.status(400).json({
        error: "A valid message is required",
      });
    }

    const response = await openai.responses.create({
      model: "gpt-4.1-mini",
      input: message,
    });

    return res.status(200).json({
      answer: response.output_text,
    });
  } catch (error) {
    console.error("AI request failed:", error);

    return res.status(500).json({
      error: "Unable to process the AI request",
    });
  }
});

app.listen(port, "0.0.0.0", () => {
  console.log(`Server listening on port ${port}`);
});

This application exposes two endpoints.

Health endpoint

GET /health

This endpoint allows the load balancer or monitoring system to check whether the application is responding.

AI endpoint

POST /api/ai

Example request:

{
  "message": "Explain how vector databases work."
}

Example response:

{
  "answer": "Vector databases store and search vector representations..."
}

The exact answer depends on the model response.

Step 4: Configure the Package Scripts

Update the relevant section of package.json:

{
  "scripts": {
    "dev": "tsx watch src/index.ts",
    "build": "tsc",
    "start": "node dist/index.js"
  }
}

Ensure your tsconfig.json compiles TypeScript into the dist directory.

For example, the relevant compiler settings can include:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "rootDir": "./src",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts"]
}

When using NodeNext, configure your package's module type and import extensions consistently with the TypeScript and Node.js versions you use. Test the compiled application before building the production image.

4. Create a Dockerfile

Now let's containerize the application.

Create a file named Dockerfile in the project root:

FROM node:22-alpine AS builder

WORKDIR /app

COPY package*.json ./

RUN npm ci

COPY tsconfig.json ./
COPY src ./src

RUN npm run build


FROM node:22-alpine AS production

WORKDIR /app

ENV NODE_ENV=production

COPY package*.json ./

RUN npm ci --omit=dev \
    && npm cache clean --force

COPY --from=builder /app/dist ./dist

USER node

EXPOSE 3000

CMD ["node", "dist/index.js"]

Let's understand the important parts.

Multi-Stage Build

The Dockerfile uses two stages.

The builder stage installs all dependencies and compiles TypeScript.

The production stage installs only production dependencies and copies the compiled JavaScript into the final image.

This helps reduce the size of the final image and avoids including the TypeScript source and development dependencies unnecessarily.

Working Directory

WORKDIR /app

This sets the working directory inside the container.

Production Dependencies

RUN npm ci --omit=dev

This installs production dependencies using the lockfile.

Non-Root User

USER node

Running the application as a non-root user reduces the impact of some security issues.

Application Port

EXPOSE 3000

This documents the port used by the application. It does not publish the port to your host automatically.

Important TypeScript Note

The Dockerfile assumes that the TypeScript configuration produces dist/index.js and that the runtime imports work correctly in the selected Node.js module configuration.

Test the image locally before deploying it.

5. Create a .dockerignore File

A .dockerignore file prevents unnecessary files from being sent to the Docker build process.

Create .dockerignore:

node_modules
dist
.env
.git
.gitignore
npm-debug.log
Dockerfile*
docker-compose*
README.md

Excluding .env is particularly important because it may contain API keys and other sensitive information.

Do not copy secrets into the image and attempt to remove them later. Use runtime configuration or a secrets manager instead.

6. Build and Test the Docker Image Locally

Before deploying to AWS, make sure the container works on your local machine.

Step 1: Build the Image

Run:

docker build -t ai-docker-aws:latest .

Docker will build the application image.

Step 2: Run the Container

Pass your API key at runtime:

docker run -d \
  --name ai-app \
  -p 3000:3000 \
  -e OPENAI_API_KEY="your_openai_api_key" \
  ai-docker-aws:latest

For local testing, you can also load environment variables from a file with Docker's --env-file option. Keep that file out of version control.

Step 3: Test the Health Endpoint

Run:

curl http://localhost:3000/health

Expected response:

{
  "status": "ok"
}

Step 4: Test the AI Endpoint

Run:

curl -X POST http://localhost:3000/api/ai \
  -H "Content-Type: application/json" \
  -d '{"message":"Explain Docker in simple terms."}'

If the API key and model configuration are valid, the application should return an AI-generated answer.

Step 5: Inspect Container Logs

Run:

docker logs ai-app

If the application fails to start, inspect the logs for missing environment variables, build errors, or dependency problems.

When you're finished testing, stop and remove the container:

docker stop ai-app
docker rm ai-app

7. Create an Amazon ECR Repository

Amazon Elastic Container Registry (ECR) is a managed container image registry.

We'll use ECR to store the Docker image so that Amazon ECS can retrieve it during deployment.

First, configure the AWS CLI and authenticate your account.

Install the AWS CLI if necessary, then configure your credentials using an appropriate authentication method.

For local development, you can use an AWS CLI profile. For production automation, prefer temporary credentials through an IAM role or an OIDC-based deployment workflow instead of long-lived access keys.

Set your AWS Region and account ID:

export AWS_REGION=ap-south-1
export AWS_ACCOUNT_ID=YOUR_AWS_ACCOUNT_ID
export ECR_REPOSITORY=ai-docker-aws

Replace YOUR_AWS_ACCOUNT_ID with your actual AWS account ID.

Create the ECR repository:

aws ecr create-repository \
  --repository-name "$ECR_REPOSITORY" \
  --region "$AWS_REGION"

If the repository already exists, you can use the existing repository instead of creating another one.

Authenticate Docker with ECR:

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

After successful authentication, Docker can push images to your ECR repository, provided your AWS identity has the required permissions.

Learn more from the official Amazon ECR Documentation.

8. Push the Docker Image to Amazon ECR

First, define the full ECR image URI:

export IMAGE_URI="$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$ECR_REPOSITORY"

Build the image with the repository URI:

docker build -t "$IMAGE_URI:latest" .

Push the image:

docker push "$IMAGE_URI:latest"

Once the push finishes, the image will be available in your ECR repository.

Use Image Tags in Production

The latest tag is convenient for a tutorial, but production deployments should use immutable, traceable image tags.

For example:

docker build -t "$IMAGE_URI:v1.0.0" .
docker push "$IMAGE_URI:v1.0.0"

A commit SHA or versioned release tag helps you identify the exact application version running in production and makes rollbacks easier.

9. Deploy the Application Using Amazon ECS and Fargate

Amazon Elastic Container Service (ECS) orchestrates container deployments.

AWS Fargate allows ECS to run containers without requiring you to manage the underlying EC2 instances.

For this tutorial, you can configure the deployment through the AWS Management Console.

Step 1: Create an ECS Cluster

  1. Open the Amazon ECS console.

  2. Choose the option to create a cluster.

  3. Enter a cluster name, such as ai-app-cluster.

  4. Create the cluster using the available Fargate-compatible configuration.

Step 2: Create a Task Definition

A task definition describes how ECS should run your container.

Create a task definition with the following configuration:

Setting

Example Value

Task definition family

ai-app-task

Launch option

AWS Fargate

Operating system

Linux

CPU architecture

Match your Docker image

CPU

0.5 vCPU

Memory

1 GB

Container name

ai-app

Container image

Your ECR image URI

Container port

3000

These CPU and memory values are starting points for a lightweight example, not universal production recommendations. AI workloads, request volume, and memory usage may require larger tasks.

Make sure the CPU architecture matches your image. For example, an ARM64 image needs a compatible runtime configuration.

Step 3: Configure the Task Execution Role

The task execution role allows ECS to perform tasks such as pulling images from ECR and sending logs to CloudWatch.

Use the appropriate execution-role permissions and ensure the role is configured for your deployment.

The execution role is different from the task role. The task role grants AWS permissions to your application code if it needs to access services such as S3 or DynamoDB.

Follow the principle of least privilege when assigning permissions.

Step 4: Configure Environment Variables and Secrets

Your application requires an OpenAI API key.

For production, store the key in AWS Secrets Manager or another suitable secrets service.

In the ECS task definition, configure the container to retrieve the secret using the supported secrets configuration.

The task execution role must have permission to retrieve the secret, and the task must have network access to the required AWS service.

Avoid placing API keys directly in the task definition as plain-text environment variables.

Step 5: Create an ECS Service

Create an ECS service using your task definition.

Configure the service with:

  • Your ECS cluster.

  • The task definition revision.

  • AWS Fargate as the launch type or capacity provider.

  • The desired number of tasks.

  • The appropriate VPC and subnets.

  • A security group.

  • Optional load-balancer integration.

For a public web application, an Application Load Balancer is generally a better option than exposing the container directly.

10. Configure an Application Load Balancer

An Application Load Balancer (ALB) can route incoming HTTP and HTTPS requests to your ECS tasks.

It also provides health checks that help ECS and the load balancer identify whether the application is responding.

Step 1: Create a Target Group

Create a target group configured for IP targets, which is appropriate for typical Fargate deployments.

Configure the target group with:

Setting

Example

Target type

IP

Protocol

HTTP

Port

3000

Health check path

/health

Success response

200

The health check endpoint should return a successful response when the application is ready to receive traffic.

For production applications, consider implementing a separate readiness check that verifies critical dependencies without making expensive external AI calls.

Step 2: Configure the Load Balancer

Create an Application Load Balancer and configure its listeners.

For production, use an HTTPS listener with a valid certificate managed through AWS Certificate Manager.

Configure the listener to forward requests to the ECS target group.

Step 3: Configure Security Groups

A common configuration is:

Load balancer security group

  • Allow inbound HTTPS traffic on port 443.

  • Allow inbound HTTP on port 80 only if you need to redirect it to HTTPS.

ECS task security group

  • Allow inbound traffic on port 3000 only from the load balancer's security group.

The ECS task should not accept unrestricted inbound traffic from the internet when the load balancer is intended to be its public entry point.

The tasks also need outbound network access to reach external LLM APIs. If you place tasks in private subnets, configure an appropriate NAT gateway or another supported egress architecture.

Remember that NAT gateways and load balancers introduce additional costs.

11. Configure Secrets Securely

AI applications frequently need credentials for external services, including:

  • OpenAI or other LLM providers.

  • Vector databases.

  • Internal APIs.

  • AWS services.

Avoid hardcoding these credentials in source code or Docker images.

Recommended Approach

  1. Store secrets in AWS Secrets Manager.

  2. Reference the secret from the ECS task definition.

  3. Grant the execution role permission to retrieve the specific secret.

  4. Restrict access to authorized users and services.

  5. Rotate credentials according to your security requirements.

If your application uses S3, DynamoDB, or other AWS services, use the ECS task role for those application-level permissions rather than embedding AWS access keys in the container.

This makes the deployment easier to manage and reduces the risk of credential exposure.

12. Monitor the Application Using CloudWatch

Deploying an application is only part of the process. You also need to monitor its behavior.

Amazon CloudWatch can collect logs and metrics from your ECS tasks.

Enable Container Logs

Configure the ECS container definition to use the awslogs log driver.

A typical configuration includes:

  • Log driver: awslogs

  • Log group: /ecs/ai-app

  • Region: Your AWS Region

  • Stream prefix: ecs

Ensure the log group exists or that the execution role has the permissions needed to create it.

What Should You Monitor?

For an AI application, consider monitoring:

  • Container CPU utilization.

  • Container memory utilization.

  • HTTP request volume.

  • API error rates.

  • LLM request latency.

  • LLM provider failures.

  • Token usage and API costs.

  • Vector database latency.

  • Timeouts and rate limits.

Avoid logging API keys, sensitive prompts, private user data, or full AI conversations unless there is a clear, authorized reason and an appropriate data-protection policy.

Use structured logs and request IDs to make troubleshooting easier.

13. Scale Your AI Application

As more users access your application, you may need to increase its capacity.

Amazon ECS supports scaling the number of running tasks.

For example, you might start with one task and increase the desired count as traffic grows.

You can configure service auto scaling based on metrics such as:

  • Average CPU utilization.

  • Average memory utilization.

  • Request count per target.

  • Other application-specific metrics.

Important Considerations for AI Applications

Scaling containers does not automatically increase your LLM provider's rate limits.

Your application may also be constrained by:

  • LLM API quotas.

  • Vector database capacity.

  • Database connection limits.

  • Network latency.

  • Token generation speed.

  • Concurrent request volume.

Use request timeouts, rate limiting, concurrency controls, and appropriate caching where suitable.

For long-running AI tasks, consider moving work into a queue-based architecture rather than keeping HTTP requests open for extended periods.

14. Common Deployment Problems and Their Solutions

Problem 1: The Container Starts but the Application Is Unreachable

Possible causes:

  • The application listens on localhost rather than 0.0.0.0.

  • The container port is incorrect.

  • The security groups block traffic.

  • The load balancer target group is misconfigured.

Solution:

Make sure the server listens on all container interfaces:

app.listen(port, "0.0.0.0");

Then verify the port mappings, task security group, target group, and load balancer listener.

Problem 2: The ECS Task Cannot Pull the Docker Image

Possible causes:

  • Incorrect ECR image URI.

  • Missing ECR permissions.

  • Incorrect task execution role.

  • Network connectivity problems.

Solution:

Verify the image URI, repository Region, execution-role permissions, and network configuration.

Inspect ECS service events for additional diagnostic information.

Problem 3: The AI API Key Is Missing

Possible causes:

  • The secret is not configured in the task definition.

  • The execution role lacks permission to retrieve it.

  • The secret's key name is incorrect.

  • The task has not been redeployed after a configuration change.

Solution:

Verify the secret configuration and permissions. Then deploy a new task revision when necessary.

Problem 4: The Application Works Locally but Fails on AWS

Possible causes:

  • Environment differences.

  • Incorrect Node.js module configuration.

  • Missing production dependencies.

  • CPU architecture mismatch.

  • Missing outbound network access.

Solution:

Test the final Docker image locally, confirm the runtime configuration, and inspect CloudWatch logs.

Problem 5: LLM Requests Are Slow or Fail

Possible causes:

  • LLM provider rate limits.

  • Network latency.

  • Invalid API credentials.

  • Provider outages.

  • Excessive prompt size.

Solution:

Implement request timeouts, bounded retries, rate limiting, and clear error handling. Monitor model latency and provider error rates.

15. Docker and AWS Deployment Best Practices

For a production AI application, follow these recommendations:

  1. Use multi-stage Docker builds to keep production images smaller.

  2. Run containers as non-root users whenever practical.

  3. Keep secrets out of images and source control.

  4. Use immutable image tags to support traceability and rollback.

  5. Configure HTTPS for public-facing applications.

  6. Restrict security group rules to the minimum required access.

  7. Use IAM roles instead of hardcoded AWS credentials.

  8. Configure health checks for service availability.

  9. Monitor logs and metrics through CloudWatch.

  10. Set request and execution limits to control resource usage and costs.

  11. Scan container images for known vulnerabilities.

  12. Use automated deployment pipelines with controlled permissions.

  13. Plan for graceful shutdowns so deployments do not interrupt active requests unnecessarily.

  14. Protect AI endpoints with authentication, authorization, and rate limiting.

  15. Estimate AWS and LLM costs before increasing capacity.

A secure deployment requires more than a working Docker image. It also needs appropriate network controls, monitoring, resource limits, and operational procedures.

16. How Much Does It Cost to Deploy an AI Application on AWS?

AWS deployment costs depend on the services you choose and how much your application uses them.

Typical cost components include:

Service

Cost Factors

Amazon ECS with Fargate

CPU, memory, task runtime, and architecture

Amazon ECR

Stored image data and data transfer

Application Load Balancer

Load balancer usage and processed traffic

Amazon CloudWatch

Log ingestion, retention, and metrics

AWS Secrets Manager

Stored secrets and API usage

NAT Gateway

Gateway runtime and data processing

LLM Provider

Model usage, input tokens, and output tokens

Vector Database

Compute, storage, and query volume

There is no single fixed price for this architecture. Costs vary by AWS Region, configuration, usage, and provider pricing.

For a development project, you can reduce expenses by using small task sizes, limiting the number of running tasks, controlling log retention, and avoiding unnecessary infrastructure.

However, some resources can continue generating charges even when your application receives little traffic. Review the current AWS pricing pages and set billing alerts before deploying.

Conclusion

Deploying an AI application using Docker and AWS provides a practical way to move from local development to a cloud-hosted service.

In this tutorial, we created a Node.js AI API, packaged it into a Docker image, pushed the image to Amazon ECR, and explored deploying it through Amazon ECS and AWS Fargate.

We also covered load balancing, secrets management, monitoring, scaling, troubleshooting, and production security.

The main deployment workflow is:

Build the application → Create a Docker image → Push to Amazon ECR → Deploy with ECS and Fargate → Configure networking and secrets → Monitor and scale.

If you're building AI applications with Node.js, LangChain, RAG, or vector databases, learning Docker and AWS will help you deploy your projects more reliably.

Start with a small application, verify every deployment step, and add production capabilities as your requirements grow.

Frequently Asked Questions (FAQs)

1. Can I deploy an AI application using Docker and AWS?

Yes. You can package your application into a Docker image, store it in Amazon ECR, and deploy it using Amazon ECS with AWS Fargate, Amazon EKS, or another compatible hosting service.

2. Why should I use Docker for AI applications?

Docker packages your application and its dependencies into a consistent environment. This makes it easier to test, deploy, and run your application across different environments.

3. What is the difference between Amazon ECS and AWS Fargate?

Amazon ECS orchestrates container workloads. AWS Fargate provides managed compute capacity for running supported containers without requiring you to manage the underlying servers.

4. Where should I store my AI API keys on AWS?

AWS Secrets Manager is a suitable option for storing sensitive API keys. You can reference secrets in your ECS task definition and grant the required access through IAM roles.

5. Can I deploy a RAG application using Docker and AWS?

Yes. You can containerize the API and retrieval logic, deploy the application on ECS, and connect it to a vector database. The vector database may run as a separate managed service or on infrastructure you operate.

6. Is AWS Fargate suitable for AI applications?

Fargate can be suitable for API-based AI applications that call external model providers. Applications that require specialized GPU hardware or custom model-serving infrastructure may need a different deployment approach.

7. How do I monitor a Dockerized AI application on AWS?

You can use Amazon CloudWatch to collect container logs and metrics, configure alarms, and monitor service health. You should also track LLM latency, failures, token usage, and API costs.

8. How can I reduce AWS deployment costs?

Choose appropriate task sizes, scale according to demand, limit log retention, remove unused resources, and monitor data transfer costs. Also track LLM usage because model calls may represent a significant portion of your application's overall expenses.

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↘