vohzd.com

Docker Part One: Create an Image From Scratch

2 min read

Docker lets you run multiple apps on one machine without the headache of conflicting dependencies and ports. Here's a dead simple walkthrough. We'll create an Express app, Dockerise it, and push it to Docker Hub.

Step 1: Install Docker

If you're on Ubuntu, the official way:

sudo apt-get remove docker docker-engine docker.io containerd runc
sudo apt-get install ca-certificates curl gnupg
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin -y

Verify it's working:

docker run hello-world

Step 2: Create an Express app

npm init -y && npm i express

Step 3: Add a start script to package.json

"scripts": {
  "start": "node index.js"
}

Step 4: Create index.js

const app = require("express")();

app.get("/", (req, res) => { res.send("Awwww yis"); });

app.listen(3000, () => console.log("Server running on port 3000"));

Step 5: Create a Dockerfile

FROM node:20-alpine
WORKDIR /src
COPY package.json .
RUN npm i
COPY . .
EXPOSE 3000
CMD ["npm", "start"]

We're using node:20-alpine, a tiny Linux distro that keeps the image size right down.

Step 6: Build the image

docker build -t your-image-name .

Check it exists with docker images.

Step 7: Run the image

docker run -p 3000:3000 -d your-image-name

Hit localhost:3000 and you should see "Awwww yis". Use docker ps to see running containers, and docker kill <name> to stop one.

Step 8: Push to Docker Hub

docker login
docker tag your-image-name yourusername/your-image-name
docker push yourusername/your-image-name

And that's it. Your image is on Docker Hub, ready to pull from anywhere.

Hint: if you ever want to nuke everything locally, run docker system prune -a. The -a flag goes nuclear.

Next up: Provision a VPS with Nginx and SSL