Deploying a REST API built with TypeScript using Docker containers is a practical approach to ensure portability, scalability, and ease of deployment. This article provides a step-by-step example to help developers understand how to containerize and deploy their TypeScript REST API efficiently.
Prerequisites
- Node.js and npm installed
- Docker installed and running
- Basic knowledge of TypeScript and Docker
- Code editor (e.g., VS Code)
Setting Up the TypeScript REST API
Create a new directory for your project and initialize a new Node.js project:
mkdir my-api && cd my-api
npm init -y
Install necessary dependencies:
npm install express typescript ts-node @types/express --save
Initialize TypeScript configuration:
npx tsc --init
Create the API Server
Create a file named index.ts:
```typescript
import express from 'express';
const app = express();
app.get('/api', (req, res) => {
res.json({ message: 'Hello from TypeScript API!' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
```
Configuring Docker
Create a Dockerfile in the root of your project:
```dockerfile
FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npx tsc
EXPOSE 3000
CMD ["node", "index.js"]
```
Building and Running the Container
Build the Docker image:
docker build -t my-typescript-api .
Run the container:
docker run -d -p 4000:3000 --name my-api-container my-typescript-api
Access the API at http://localhost:4000/api.
Conclusion
Containerizing a TypeScript REST API with Docker simplifies deployment and scaling. This setup allows you to deploy your API consistently across different environments, making it ideal for production use. Experiment with adding more endpoints and integrating databases to build more complex applications.