We got the sample code to the point where we could run it as a container last time. This time, we want to create applications for other roles, so we will set up a hierarchy to manage them.
Organize Projects
Copy the application described in the previous blog posts, this time to the folder src/playwright.
Creating .env files
Create an .env file so that you can manage all the environment variables used in this project at once. In this case, we set the following.
COMPOSE_PROJECT_NAME=search-utility
PROJECT_VERSION=0.1.0
PLAYWRIGHT_IMAGE=mcr.microsoft.com/playwright:v1.38.1-jammy
PAGE_WIDTH=1280
PAGE_HEIGHT=800
PAGE_WAIT_TIME=2000
For the above, also prepare a .env.example with no values set.
Creating a .gitignore
The following code should be included.
node_modules
dist
.env
Creating docker-compose.yml
We want to automate as much as possible the parts related to container image creation and startup, so we create this file.
services:
playwright:
image: ${COMPOSE_PROJECT_NAME}-playwright:${PROJECT_VERSION}
platform: linux/amd64
build:
context: ./src/playwright
args:
PARENT_IMAGE: ${PLAYWRIGHT_IMAGE}
environment:
PAGE_WIDTH: ${PAGE_WIDTH}
PAGE_HEIGHT: ${PAGE_HEIGHT}
PAGE_WAIT_TIME: ${PAGE_WAIT_TIME}
ports:
- "3000:3000"
networks:
- default
Here, the .env file is referenced and defined by passing the project name, version, docker image file name, and various values.
Modification of Docker files
The values of the environment settings defined in the .env file, which can then be read through the docker-compose.yml file, should be rewritten as follows
ARG PARENT_IMAGE
FROM ${PARENT_IMAGE}
WORKDIR /usr/app
COPY . /usr/app
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
RUN cd /usr/app \
&& npm install \
&& npm run build
CMD ["npm","run","start"]
Modification of screenshot.ts file
To use environment variables in this file as well, rewrite the code as follows. First, add the following code so that the value of the environment setting can be referenced
const PAGE_WAIT_TIME = parseInt(process.env.PAGE_WAIT_TIME || "2000");
const PAGE_WIDTH = parseInt(process.env.PAGE_WIDTH || "1280");
const PAGE_HEIGHT = parseInt(process.env.PAGE_HEIGHT || "800");
Change the actual code to use the following
await page.setViewportSize({ width: PAGE_WIDTH, height: PAGE_HEIGHT });
await page.goto(urlParam);
await page.waitForTimeout(PAGE_WAIT_TIME);
Confirmation of operation
After the above configuration changes are complete, run docker compose build.
The image has been successfully created. Then run docker compose up -d.
Summary
The project itself has been reorganized in order to prepare from now on for something other than containers using Playwright. The sample code is available in the following repository branch.