We will set up the sample application we have created so far to work with Docker. This is not a particularly elaborate story, but rather just an introduction to the general Docker procedure.
Creating a Dockerfile
First, create a dockerfile so that you can create a base container image. In this case, we configured the following settings.
FROM node:20-bullseye
WORKDIR /usr/app
COPY . /usr/app
RUN cd /usr/app \
&& npm install \
&& npm run build
CMD ["npm","run","start"]
It is a simple container image of Node.js that you can copy the sample to and run it. To actually build this image, you can use the command, right-click on the Dockerfile in Visual Studio Code, and execute "Build" as is. After a few moments, the image will be ready.
Run the container you created.
docker run -p 3000:3000 -d sitecoresearchnextjssample
Once the container is up and running, the 3000 port can be accessed to access the sample app.
Creating a docker-compose file
Then, to speed up the build and startup process, we will create a docker-compose.yml file and make it work with docker compose.
First, add information about the image file and project to the .env definition.
COMPOSE_PROJECT_NAME=search-nextjs
PROJECT_VERSION=0.3.0
NODEJS_PARENT_IMAGE=node:20-bullseye
NEXT_PUBLIC_SEARCH_ENV=
NEXT_PUBLIC_SEARCH_CUSTOMER_KEY=
NEXT_PUBLIC_SEARCH_API_KEY=
NEXT_PUBLIC_SEARCH_PATH=/
Then, create the docker-compose.yaml file as follows
services:
nextsearch:
image: ${COMPOSE_PROJECT_NAME}:${PROJECT_VERSION}
platform: linux/amd64
build:
context: .
args:
PARENT_IMAGE: ${NODEJS_PARENT_IMAGE}
environment:
NEXT_PUBLIC_SEARCH_ENV: ${NEXT_PUBLIC_SEARCH_ENV}
NEXT_PUBLIC_SEARCH_CUSTOMER_KEY: ${NEXT_PUBLIC_SEARCH_CUSTOMER_KEY}
NEXT_PUBLIC_SEARCH_API_KEY: ${NEXT_PUBLIC_SEARCH_API_KEY}
NEXT_PUBLIC_SEARCH_PATH=: ${NEXT_PUBLIC_SEARCH_PATH}
ports:
- "3000:3000"
networks:
- default
Finally, the Dockerfile is rewritten as follows to retrieve the image information from the environment configuration file.
ARG PARENT_IMAGE
FROM ${PARENT_IMAGE}
WORKDIR /usr/app
COPY . /usr/app
RUN cd /usr/app \
&& npm install \
&& npm run build
CMD ["npm","run","start"]
Now that we are ready, we can run docker compose build to create the image, docker compose up -d to start the container, and we can access the app just as we did the first time we started the container.
Summary
Docker can now be used during development and as an operation check before deploying to vercel. Since it is easy to prepare a local operating environment, including operation checks, we have introduced a procedure for containerization and operation.