Docker  >  Setting up Docker Files

Setting up Docker Files

Assuming that you have already installed the docker app on my computer and have it running and your NextJS project is already set up.

Create Dockerfile

In your NextJS project, create a 'Dockerfile' file and paste the following:

This will create a docker image using Node (V22 in code) and either build the Docker Image using the project or run the image on port localhost:3000

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
### /Dockerfile # ---- Build stage ---- FROM node:22-alpine AS builder WORKDIR /app ENV NODE_ENV=production # Install dependencies with clean, repeatable lockfile install COPY package*.json ./ RUN npm ci # Copy source and build COPY . . RUN npm run build # ---- Runtime stage ---- FROM node:22-alpine AS runner WORKDIR /app ENV NODE_ENV=production # Next.js needs these at runtime ENV PORT=3000 ENV HOSTNAME=0.0.0.0 # Only copy what the server needs to run COPY package*.json ./ RUN npm ci --omit=dev COPY --from=builder /app/.next ./.next COPY --from=builder /app/public ./public # If you have next.config.js (or similar runtime files), include them: COPY next.config.js ./ EXPOSE 3000 # Ensure your package.json has: "start": "next start -p 3000 -H 0.0.0.0" CMD ["npm", "start"]

Create Docker Compose

This file references the app image from Dockerfile and the mongo image from DockerHub. Follow image setup process for other needed images.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
### /docker.compose.yml version: "3.8" services: app: build: . ports: - "3000:3000" env_file: - .env environment: - MONGODB_URI=<MONGO_DB_URL> # depends_on: # - mongo # mongo: # image: mongo # ports: # - "27017:27017" # environment: # MONGO_INITDB_ROOT_USERNAME: admin # MONGO_INITDB_ROOT_PASSWORD: password #mongo-express: # image: mongo-express # ports: # - "8081:8081" # environment: # ME_CONFIG_MONGODB_SERVER: mongo # ME_CONFIG_MONGODB_ADMINUSERNAME: admin # ME_CONFIG_MONGODB_ADMINPASSWORD: password # ME_CONFIG_MONGODB_AUTH_DATABASE: admin # depends_on: # - mongo

I have commented out the mongo and mongo-express image for builds as I don't need to test this app on a local mongo database.

Create Docker Ignore

This file is similar to a .gitignore and will mostly ignore the same files.

1
2
3
4
5
6
7
8
9
10
node_modules .next .git .gitignore Dockerfile docker-compose* README.md *.log .env .env.*

🙌 Congrats, you have completed setting up Docker in your NextJS project!