Site icon APPECODE

How to Dockerize Your Python, Node.js, or Rust App

APPECODE - Cybersecurity While Travelling

APPECODE - Cybersecurity While Travelling

How to Dockerize Your Python, Node.js, or Rust App

Introduction

Docker makes it easy to package your application and its dependencies into a single container that can run consistently across environments. This tutorial shows you how to create a Dockerized version of a simple application built in Python, Node.js, or Rust. We’ll walk through writing a Dockerfile and running your app in a container.

Step 1: Install Docker

If you haven’t already, install Docker from the official site: docker.com/products/docker-desktop. Once installed, verify with:

docker --version

Step 2: Create a Simple App

Use one of these examples based on your language of choice:

Python (app.py):

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello from Python!"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

Node.js (index.js):

const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello from Node.js!'));
app.listen(5000, () => console.log('Server running on port 5000'));

Rust (main.rs using Rocket):

#[macro_use] extern crate rocket;

#[get("/")]
fn index() -> &'static str {
    "Hello from Rust!"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
}

Step 3: Write a Dockerfile

Create a file named Dockerfile in the root of your project directory. Here are Dockerfile examples for each language:

Python Dockerfile:

FROM python:3.10
WORKDIR /app
COPY . .
RUN pip install flask
CMD ["python", "app.py"]

Node.js Dockerfile:

FROM node:18
WORKDIR /app
COPY . .
RUN npm install
CMD ["node", "index.js"]

Rust Dockerfile (with cargo):

FROM rust:latest
WORKDIR /app
COPY . .
RUN cargo build --release
CMD ["./target/release/your_binary"]

Step 4: Build and Run the Docker Container

In your terminal, build the image using:

docker build -t myapp .

Then run it with:

docker run -p 5000:5000 myapp

This maps port 5000 from the container to your host. Open a browser and go to http://localhost:5000.

Conclusion

You’ve successfully containerized a basic app in Python, Node.js, or Rust. Docker helps ensure consistency across development and production, and it’s a critical skill in modern DevOps workflows. You can now extend this by adding volumes, environment variables, and multi-stage builds for optimization.

Exit mobile version