What You'll Learn
Beginner
- How to write a Dockerfile
- How to build an image from a Dockerfile
- The core instructions: FROM, COPY, RUN, CMD
The Docker workflow: Dockerfile → Image → Container → Registry
The Dockerfile
A Dockerfile is a text file with instructions to build an image.
Dockerfiledockerfile
FROM node:18-alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]What Each Instruction Does
| Instruction | What it does |
|---|---|
FROM | Base image to start from (required, must be first) |
WORKDIR | Sets the working directory |
COPY | Copies files from host into the image |
RUN | Runs a command during build (creates a layer) |
EXPOSE | Documents which port the container listens on |
CMD | Default command when the container starts |
Building the Image
Terminalbash
# Build an image tagged "myapp:1.0"
docker build -t myapp:1.0 .
# The "." is the build contextRunning Your Image
Terminalbash
docker run -d -p 3000:3000 --name my-app myapp:1.0
curl http://localhost:3000The dot matters
The . at the end of docker build is the build context — the directory Docker sends to the daemon. COPY . . copies from this context..dockerignore
.dockerignoretext
node_modules
npm-debug.log
.git
.env
Dockerfile
docker-compose.yml
*.mdPractical Exercise
Create a directory:
mkdir myapp && cd myappCreate
server.js with a simple HTTP serverCreate
package.jsonCreate the Dockerfile
Build:
docker build -t myapp:1.0 .Run:
docker run -d -p 3000:3000 myapp:1.0Key Takeaways
- A Dockerfile is a text file with build instructions. Each line creates a layer.
- Core instructions: FROM, COPY, RUN, CMD.
docker build -t name:tag .builds an image.- The
.is the build context. - Always use
.dockerignoreto exclude unnecessary files.
Comments
Comments
Post a Comment