Artificial Intelligence

How to Deploy an AI Application Using Docker and VPS

Deploying an AI application doesn't have to be complicated or expensive. If you're building an AI chatbot, a Retrieval-Augmented Generation (RAG) system, or an…

D
DevByteTechnical Author
Published
14 min read0 views
How to Deploy an AI Application Using Docker and VPS

Deploying an AI application doesn't have to be complicated or expensive. If you're building an AI chatbot, a Retrieval-Augmented Generation (RAG) system, or an application powered by an LLM API, a Virtual Private Server (VPS) combined with Docker can provide a practical and flexible deployment solution.

With Docker, you can package your application and its dependencies into a consistent environment. A VPS gives you control over the server, networking, and deployment process.

In this guide, you'll learn how to deploy a Node.js AI application using Docker on a Linux VPS, configure Nginx as a reverse proxy, enable HTTPS, and apply essential production security practices.

What You'll Learn

  • What a VPS is and why it's useful for AI applications

  • How Docker simplifies deployment

  • How to prepare a Linux VPS

  • How to containerize a Node.js AI application

  • How to deploy the application on your server

  • How to configure Nginx and HTTPS

  • How to manage environment variables and secrets

  • How to troubleshoot common deployment problems

1. What Is a VPS?

A Virtual Private Server (VPS) is a virtual machine running on a physical server. It provides dedicated virtual resources, such as CPU, memory, and storage, along with administrative control over its operating system.

Popular VPS providers include:

  • DigitalOcean

  • Hetzner

  • Hostinger

  • Linode

  • Vultr

A VPS can be a good choice for hosting AI applications that call external LLM APIs, run lightweight embedding models, or serve a RAG backend.

However, running large language models locally requires considerably more RAM and potentially a GPU. Before choosing a server, estimate your application's memory, CPU, storage, and concurrency requirements.

2. Why Use Docker for AI Application Deployment?

Docker packages an application and its dependencies into a container image. The same image can then run across development, testing, and production environments.

Without Docker, you might need to install and configure the correct Node.js version, system packages, and application dependencies manually on every server.

Docker makes this process more consistent.

Benefits of Docker

Consistent environments: Your application runs with the dependencies defined in its image.

Simpler deployment: You can build an image and deploy it to different servers.

Dependency isolation: Application dependencies remain separate from the host system.

Easier updates: You can replace a running container with a new version of your application.

Service separation: Your API, vector database, and other components can run as separate services.

Docker doesn't automatically make an application secure or scalable, but it provides a useful foundation for managing deployments.

3. Understand the Deployment Architecture

For this tutorial, we'll use the following architecture:

                   Users
                     |
                     v
              Domain / DNS
                     |
                     v
              Nginx + HTTPS
                     |
                     v
             Node.js AI API
              (Docker)
                     |
             +-------+-------+
             |               |
             v               v
        LLM Provider     Vector Database
        External API     Optional Service

The Node.js application handles incoming requests and communicates with an external LLM provider. If the application implements RAG, it can also retrieve relevant information from a vector database.

Nginx receives public HTTP and HTTPS traffic and forwards valid requests to the application.

For this example, we'll deploy a simple Node.js API that calls an external AI provider. You can adapt the same structure for LangChain, LangGraph, or a RAG application.

4. Prepare Your VPS

First, create a VPS with a supported Linux distribution, such as Ubuntu LTS.

Connect to the server through SSH:

ssh username@YOUR_SERVER_IP

Replace username and YOUR_SERVER_IP with your actual SSH username and server IP address.

Update the package lists and install available updates:

sudo apt update
sudo apt upgrade -y

Install the utilities required for downloading and managing packages:

sudo apt install -y ca-certificates curl git

Configure the Firewall

Allow SSH, HTTP, and HTTPS traffic:

sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable

Important: Confirm that SSH access is permitted before enabling the firewall. Otherwise, you could lock yourself out of the server.

Also configure the VPS provider's network firewall, if available, to allow only the ports your application needs.

We'll keep the Node.js application port private instead of exposing it directly to the internet.

5. Install Docker on the VPS

Docker will run your AI application inside a container.

For Ubuntu, follow Docker's official installation instructions:

https://docs.docker.com/engine/install/ubuntu/

After installation, verify that Docker is working:

sudo systemctl status docker

Check the installed version:

sudo docker --version

Run a test container:

sudo docker run --rm hello-world

If the command completes successfully, Docker is ready to use.

You can use Docker Compose to manage applications that require multiple services. Install the Compose plugin by following the official documentation:

https://docs.docker.com/compose/install/linux/

Verify it:

sudo docker compose version

For security, avoid giving untrusted users access to the Docker socket. Membership in the Docker group effectively grants root-level control over the host.

6. Create a Node.js AI Application

Let's create a small Node.js API that accepts a prompt and sends it to an external AI provider.

Create a project directory:

mkdir ai-vps-app
cd ai-vps-app

Initialize the project:

npm init -y

Install the required dependencies:

npm install express openai dotenv

Configure the project to use ES modules by adding "type": "module" to package.json.

For example:

{
  "name": "ai-vps-app",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "dotenv": "^16.0.0",
    "express": "^4.0.0",
    "openai": "^5.0.0"
  }
}

The dependency versions above illustrate the configuration format. Keep the versions installed in your project consistent with your lockfile rather than replacing working versions blindly.

Create the Server

Create a file named server.js:

import express from "express";
import OpenAI from "openai";
import "dotenv/config";

const app = express();

app.use(express.json({ limit: "20kb" }));

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

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

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

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

    if (
      typeof prompt !== "string" ||
      prompt.trim().length === 0 ||
      prompt.length > 4000
    ) {
      return res.status(400).json({
        error: "Provide a valid prompt of up to 4000 characters.",
      });
    }

    const response = await client.responses.create({
      model: process.env.OPENAI_MODEL || "gpt-4.1-mini",
      input: prompt,
    });

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

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

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

This example uses an external AI API, so the VPS doesn't need a GPU to run the language model itself.

The selected model must be available to your API account. Check your provider's current model documentation and use a supported model if the example model is unavailable.

For production, also implement authentication, request rate limiting, usage limits, timeouts, and appropriate error handling.

7. Store Environment Variables Securely

Create a .env file in the project directory:

PORT=3000
OPENAI_API_KEY=your_api_key_here
OPENAI_MODEL=gpt-4.1-mini

Replace the example API key with your actual key.

Never commit .env files to Git or include secrets in Docker images.

Add a .gitignore file:

node_modules/
.env
npm-debug.log*

If the project is already tracked by Git, remember that adding a file to .gitignore doesn't remove it from the repository's history.

For a production VPS, you can supply environment variables through a protected deployment configuration instead of keeping secrets in the source repository.

8. Create a Dockerfile

Now we'll package the Node.js application into a Docker image.

Create a file named Dockerfile:

FROM node:22-alpine

ENV NODE_ENV=production

WORKDIR /app

COPY package*.json ./

RUN npm ci --omit=dev

COPY --chown=node:node server.js ./

USER node

EXPOSE 3000

CMD ["node", "server.js"]

This Dockerfile uses a Node.js Alpine image, installs dependencies from the lockfile, copies the application code, and runs the process as a non-root user.

The npm ci command requires a valid package-lock.json. Generate and commit the lockfile before building the image:

npm install

For more complex applications, copy any additional required files and ensure the build process includes them.

Create a .dockerignore File

Create .dockerignore to prevent unnecessary files from entering the Docker build context:

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

This reduces the build context and helps prevent accidental inclusion of local dependencies or secrets.

9. Build and Test the Docker Image

Build the image:

sudo docker build -t ai-vps-app:1.0 .

Check that it exists:

sudo docker images

Run the container locally on the VPS:

sudo docker run -d \
  --name ai-vps-app \
  --restart unless-stopped \
  --env-file .env \
  -p 127.0.0.1:3000:3000 \
  ai-vps-app:1.0

Notice this part:

-p 127.0.0.1:3000:3000

It binds the published port to the VPS's loopback interface. Nginx on the same server can access the application, but remote users cannot directly connect to that port through the network.

Check the running container:

sudo docker ps

View its logs:

sudo docker logs ai-vps-app

Test the health endpoint from the VPS:

curl http://127.0.0.1:3000/health

Expected response:

{
  "status": "ok"
}

If you receive the expected response, the container is running and the API is reachable locally.

10. Configure Nginx as a Reverse Proxy

Nginx will receive incoming requests and forward them to the Node.js application.

Install Nginx:

sudo apt install -y nginx

Create a server configuration:

sudo nano /etc/nginx/sites-available/ai-vps-app

Add the following configuration, replacing api.example.com with your actual subdomain:

server {
    listen 80;
    listen [::]:80;

    server_name api.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;

        proxy_http_version 1.1;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_connect_timeout 10s;
        proxy_read_timeout 60s;
    }
}

Enable the configuration:

sudo ln -s \
  /etc/nginx/sites-available/ai-vps-app \
  /etc/nginx/sites-enabled/ai-vps-app

Validate the configuration:

sudo nginx -t

If validation succeeds, reload Nginx:

sudo systemctl reload nginx

Before continuing, configure your domain's DNS so that api.example.com points to your VPS's public IP address. DNS changes can take time to propagate.

You should now be able to test the API over HTTP, provided DNS and firewall configuration are correct.

11. Enable HTTPS with Let's Encrypt

HTTPS encrypts traffic between clients and your server. It is essential when your application handles authentication tokens, user data, or AI prompts.

Install Certbot and its Nginx integration:

sudo apt install -y certbot python3-certbot-nginx

Request a certificate:

sudo certbot --nginx -d api.example.com

Follow the prompts to complete the setup.

Test automatic renewal:

sudo certbot renew --dry-run

Your API should now be accessible through HTTPS:

https://api.example.com

Make sure your DNS record points to the correct server and that inbound ports 80 and 443 are accessible before requesting the certificate.

12. Test the Deployed AI API

Check the health endpoint:

curl https://api.example.com/health

Then test the chat endpoint:

curl -X POST https://api.example.com/api/chat \
  -H "Content-Type: application/json" \
  -d '{"prompt":"Explain vector databases in simple terms."}'

A successful request should return JSON containing an answer field.

If the request fails, check the application logs:

sudo docker logs --tail 100 ai-vps-app

Check the Nginx service:

sudo systemctl status nginx

And inspect recent Nginx errors:

sudo tail -n 100 /var/log/nginx/error.log

These logs often reveal missing environment variables, upstream connection errors, invalid API credentials, or provider-side failures.

13. Deploy Application Updates

When you update your application code, rebuild the image:

sudo docker build -t ai-vps-app:2.0 .

Stop and remove the existing container:

sudo docker stop ai-vps-app
sudo docker rm ai-vps-app

Start the new version:

sudo docker run -d \
  --name ai-vps-app \
  --restart unless-stopped \
  --env-file .env \
  -p 127.0.0.1:3000:3000 \
  ai-vps-app:2.0

Verify that the application is healthy:

curl http://127.0.0.1:3000/health

This is a simple deployment process suitable for a small project. However, stopping the old container before starting the new one can cause downtime.

For more reliable deployments, consider Docker Compose, automated CI/CD, health checks, and a deployment strategy that can switch traffic between versions. Back up persistent data before making changes, and avoid deleting volumes unless you intend to remove their contents.

14. Use Docker Compose for Easier Management

Docker Compose is useful when your application needs multiple services, such as an API, Redis, or a vector database.

Create a compose.yaml file:

services:
  ai-api:
    build: .
    container_name: ai-vps-app
    restart: unless-stopped
    env_file:
      - .env
    ports:
      - "127.0.0.1:3000:3000"

Start the application:

sudo docker compose up -d --build

View its status:

sudo docker compose ps

View logs:

sudo docker compose logs -f ai-api

Stop the service:

sudo docker compose down

Compose makes it easier to manage a group of related containers using one configuration file.

If you add a database or vector database, configure persistent storage, backups, network isolation, and access controls. Do not expose database ports publicly unless there is a specific, secured reason to do so.

15. Production Security Best Practices

A successful deployment is more than a running container. AI applications may process sensitive prompts, consume paid API credits, and expose business data, so security and operational controls matter.

Protect API Keys

  • Keep API keys out of source control.

  • Do not expose provider keys in frontend JavaScript.

  • Restrict access to deployment environment files.

  • Rotate credentials if they are accidentally exposed.

Add Authentication and Rate Limiting

An unprotected AI endpoint can be abused to generate unexpected provider costs.

Implement authentication where appropriate, rate limiting, request-size limits, per-user quotas, and usage monitoring.

Run Containers as Non-Root Users

Use a non-root user inside the container whenever practical. The example Dockerfile already includes this basic protection.

Keep Software Updated

Regularly update your operating system, Docker Engine, base images, and application dependencies. Rebuild and test images when security updates are available.

Monitor Resource Usage

Useful commands include:

sudo docker stats

Check available memory:

free -h

Check disk usage:

df -h

These commands help identify resource pressure, but production systems should also have suitable alerts and centralized logs.

Back Up Persistent Data

If your application uses MongoDB, PostgreSQL, ChromaDB, uploaded files, or other persistent storage, configure appropriate backups and test restoration procedures.

A Docker image alone does not back up your application's data.

16. Common Deployment Problems and Solutions

Problem 1: Container Exits Immediately

Inspect the logs:

sudo docker logs ai-vps-app

Common causes include missing environment variables, invalid configuration, missing dependencies, or application startup errors.

Problem 2: Nginx Returns 502 Bad Gateway

Check whether the application is running:

sudo docker ps

Test the local endpoint:

curl http://127.0.0.1:3000/health

Also confirm that Nginx's proxy_pass address matches the port published by Docker.

Problem 3: AI Provider Returns an Authentication Error

Check that OPENAI_API_KEY is correctly configured and that the key is valid for your provider account.

Avoid printing secrets into logs while debugging.

Problem 4: The VPS Runs Out of Memory

Check memory usage:

free -h
sudo docker stats

Possible solutions include optimizing the application, limiting concurrency, increasing server memory, or moving memory-intensive inference workloads to a suitable machine.

If you're running a local LLM, remember that model size, quantization, context length, and concurrent requests can substantially affect memory requirements.

Problem 5: The Application Works Locally but Not Through the Domain

Check:

  • Whether the DNS record points to the correct IP

  • Whether ports 80 and 443 are allowed

  • Whether Nginx configuration is valid

  • Whether the TLS certificate is active

  • Whether the Docker container is healthy

Test each layer separately to narrow down the problem.

17. VPS vs. Managed Cloud Services for AI Deployment

A VPS is not the only way to deploy an AI application.

Feature

VPS with Docker

Managed Cloud Platform

Initial setup

Requires server configuration

Often simpler

Infrastructure control

High

Depends on the platform

Server maintenance

Mostly your responsibility

Some maintenance is managed

Scaling

Often requires manual configuration

May offer managed scaling

Cost structure

Often a predictable base server cost

Varies by usage and service

Best suited for

Small to medium applications and custom deployments

Applications needing managed infrastructure or integrated cloud services

For a developer building a portfolio project, AI chatbot, or small RAG application, a VPS can be an excellent starting point.

For applications requiring high availability, complex scaling, or specialized GPU infrastructure, evaluate managed services and dedicated inference options as well.

Actual costs depend on the VPS plan, storage, traffic, backups, AI API usage, and other services.

18. When Should You Use a VPS for AI Applications?

A VPS is a good option when:

  • Your application calls an external LLM API.

  • You want to host a Node.js or Python backend.

  • You need control over Nginx, Docker, and the operating system.

  • You want to host a small RAG application.

  • You need to run supporting services such as Redis.

  • You are comfortable managing server updates and security.

A basic VPS may not be sufficient when you're hosting large local models, handling high request volumes, or requiring strict availability guarantees. In those cases, benchmark the workload and choose infrastructure accordingly.

Frequently Asked Questions

1. Can I deploy an AI application on a VPS?

Yes. You can deploy AI applications on a VPS using Docker, Node.js, Python, and external AI APIs. The server's CPU and memory requirements depend on the application and its workload.

2. Do I need a GPU to run an AI application on a VPS?

No, not if your application sends requests to an external AI provider. A GPU may be necessary or beneficial when running certain models locally.

3. Can I deploy a RAG application using Docker on a VPS?

Yes. You can containerize the RAG backend and run supporting services, such as a vector database, on the VPS. Choose sufficient memory and storage, configure persistent volumes, and protect the database from public access.

4. Is Docker necessary for VPS deployment?

No. You can install Node.js and run your application directly on the VPS. Docker is useful because it packages dependencies and makes deployment more consistent.

5. Can I host multiple applications on one VPS?

Yes. You can run multiple containers and configure Nginx to route different domains or subdomains to the appropriate services. Ensure the VPS has enough CPU, memory, and storage for all applications.

6. How do I keep my Docker application running after a reboot?

A Docker restart policy, such as unless-stopped, can restart the container when Docker starts. You should also ensure that the Docker service is enabled and that your application handles startup failures correctly.

7. Is a VPS cheaper than AWS for AI applications?

It depends on the workload and the services required. A VPS may offer predictable infrastructure pricing, while AWS offers a broad range of managed services with different billing models. Compare total infrastructure costs, maintenance effort, storage, backups, and AI provider usage.

Conclusion

Deploying an AI application using Docker and a VPS gives developers a practical way to host AI-powered APIs without immediately adopting a complex cloud architecture.

By preparing a Linux server, containerizing a Node.js backend, configuring Nginx, enabling HTTPS, and protecting environment variables, you can establish a solid foundation for an AI application.

As your application grows, consider automated deployments, monitoring, backups, stronger access controls, and a deployment strategy that minimizes downtime.

Start with a small, well-monitored deployment, measure its actual resource usage, and scale the infrastructure as your requirements evolve.

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↘