- Scenario: You want to create a Docker image for a Node.js application. Write a Dockerfile that installs Node.js and runs the application on port 3000.
Code:
FROM node:14
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
- Scenario: You want to create a Docker image for a Python application. Write a Dockerfile that installs Python and runs the application on port 5000.
Code:
FROM python:3.9
WORKDIR /app
COPY requirements.txt ./
RUN pip install -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["python", "app.py"]
- Scenario: You want to optimize the size of your Docker image by removing unnecessary files. Write a Dockerfile that only includes the necessary files and dependencies for your application.
Code:
FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY dist ./dist
EXPOSE 3000
CMD ["npm", "start"]
- Scenario: You want to use environment variables to configure your Docker container. Write a Dockerfile that sets environment variables and uses them in the application.
Code:
FROM node:14
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
ENV PORT=3000
ENV DB_URI=mongodb://localhost/mydb
EXPOSE $PORT
CMD ["npm", "start"]
- Scenario: You want to create a multi-stage Dockerfile for your application. Write a Dockerfile that builds and compiles the application in one stage and copies the compiled files into a second stage for the final image.
Code:
FROM node:14 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY --from=builder /app/dist ./dist
EXPOSE 3000
CMD ["npm", "start"]
These scenario-based questions can help you practice and become more comfortable with Dockerfile and containerization. Remember to use best practices and follow the standard Docker workflow to ensure efficient containerization and high application performance.