Lesson 10: Copying Code and Setting the Working Directory
To build an image for a real application, we need to copy our code into the image filesystem and define where our application should run.
1. WORKDIR (Working Directory)
The WORKDIR instruction sets the current working directory for subsequent instructions (RUN, CMD, ENTRYPOINT, COPY). If the directory doesn't exist, Docker will create it.
dockerfile
Good practice: Create a dedicated directory for the app
WORKDIR /app
Subsequent RUN commands will now execute inside /app
RUN pwd
Output: /app
2. COPY (Copying Files)
The COPY instruction copies files or directories from the build context (your local machine) into the image filesystem.
Syntax: COPY <source> <destination>
Example: Containerizing a Node.js Application
Assume you have a package.json and a server file (server.js).
dockerfile FROM node:20-alpine
1. Set the working directory
WORKDIR /usr/src/app
2. Copy dependency files first (for layer caching optimization!)
We copy package*.json separately so if only the code changes,
the expensive 'npm install' step is still cached.
COPY package*.json ./
3. Install dependencies
RUN npm install
4. Copy the rest of the application code
COPY . .
5. Define the application entry point
CMD ["node", "server.js"]
Difference between COPY and ADD:
COPYis generally preferred as it is simpler and clearer.ADDhas additional functionality: it can handle remote URLs and automatically extract compressed archives (tar, gzip). UseCOPYunless you explicitly need the archive extraction feature.