In modern software development, deploying applications efficiently and reliably is crucial. Combining tools like TypeScript, Travis CI, and Kubernetes offers a powerful workflow for continuous integration and deployment. This article walks through a real-world example of deploying a TypeScript application using Travis CI and Kubernetes.

Prerequisites

  • Basic knowledge of TypeScript and Node.js
  • Account setup for Travis CI and Kubernetes
  • Docker installed locally for containerization
  • kubectl configured to access your cluster

Step 1: Prepare Your TypeScript Application

Start by creating a simple TypeScript app. Ensure you have a tsconfig.json and a package.json with necessary scripts. For example, your package.json might include:

scripts: { "build": "tsc", "start": "node dist/index.js" }

Your source code should be in a src folder, and the build output in a dist folder.

Step 2: Containerize the Application

Create a Dockerfile to containerize your app. An example Dockerfile:

FROM node:14-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["node", "dist/index.js"]

Step 3: Set Up Travis CI Configuration

Create a .travis.yml file in your project root. This file defines the build and deployment process:

language: node_js
node_js:
  - '14'
services:
  - docker
before_install:
  - npm install
script:
  - npm run build
after_success:
  - docker build -t your-dockerhub-username/your-app-name .
  - echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin
  - docker push your-dockerhub-username/your-app-name
deploy:
  provider: script
  script: kubectl apply -f k8s/deployment.yaml
  on:
    branch: main

Step 4: Configure Kubernetes Deployment

Create a deployment.yaml file in a k8s directory. This file defines how your app runs in Kubernetes:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: ts-app-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: ts-app
  template:
    metadata:
      labels:
        app: ts-app
    spec:
      containers:
      - name: ts-app
        image: your-dockerhub-username/your-app-name
        ports:
        - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: ts-app-service
spec:
  type: LoadBalancer
  selector:
    app: ts-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000

Step 5: Automate Deployment

Trigger the Travis CI build on your main branch. Upon successful build, Travis will push the Docker image to Docker Hub and deploy the updated app to Kubernetes using kubectl apply.

Conclusion

This setup enables continuous integration and deployment for your TypeScript app. With Travis CI automating builds and Docker images, and Kubernetes managing deployment, you ensure a reliable and scalable production environment.