This content originally appeared on DEV Community and was authored by Yash Sonawane
“Ready to become a Docker chef? In this episode, weβll write your first Dockerfile β the recipe that creates your own custom container. Simple, step-by-step, with a real app. Letβs cook!
“
What is a Dockerfile?
A Dockerfile is like a recipe card for Docker. It tells Docker exactly how to build an image from scratch.
Just like:
- A cake recipe includes ingredients and steps
- A Dockerfile includes base image, dependencies, code, and commands
Once Docker reads the Dockerfile, it builds a Docker image, which you can then run as a container.
Let’s Build Your First Dockerfile
Weβll dockerize a basic Node.js app.
Project Structure:
my-node-app/
βββ Dockerfile
βββ package.json
βββ index.js
index.js
(your app):
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello from Docker!');
});
server.listen(3000, () => console.log('Server running on port 3000'));
package.json
:
{
"name": "my-node-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
}
}
Writing the Dockerfile
Now create a file called Dockerfile
(no extension!) and add this:
# Base image
FROM node:18
# Working directory
WORKDIR /app
# Copy files
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy app source
COPY . .
# Expose port
EXPOSE 3000
# Start the app
CMD ["npm", "start"]
Build & Run the Docker Image
Build the image:
docker build -t my-node-app .
Run the container:
docker run -d -p 3000:3000 my-node-app
Open your browser:
Visit http://localhost:3000
β youβll see: Hello from Docker!
What Did We Just Do?
-
FROM
: Sets the base environment (Node.js) -
WORKDIR
: The folder where your code lives inside the container -
COPY
: Moves your code into the container -
RUN
: Installs dependencies -
EXPOSE
: Lets Docker know what port the app uses -
CMD
: Tells Docker how to start the app
Bonus Tips
- Use
.dockerignore
to skipnode_modules
,logs
, etc. - Always pin your base image (
node:18
not justnode
) - Keep Dockerfiles short, clean, and readable
Up Next: Docker CLI Mastery
In Episode 5, weβll explore:
- Most used Docker commands
- How to manage images and containers
- Tricks to make your Docker life easier
Letβs Build Together
Have you written your first Dockerfile? Did it work? Run into any errors?
Comment below β Iβm here to help every beginner succeed
If you learned something new today, show some love with a like or drop a comment. Share this episode with your Dev.to fam!
Next: βDocker CLI Cheat Sheet β 15 Commands Youβll Actually Useβ
This content originally appeared on DEV Community and was authored by Yash Sonawane