기본 콘텐츠로 건너뛰기

How to make the latest version of Headless CMS STRAPI into a docker image and upload it to the synopsis for service.

In the past, it was popular to create cafes (bulletin boards) and blogs and provide services using CMS (content management systems) such as Zero Board and WordPress. Due to the development of the Frontend, the Headless CMS, which is currently serviced mainly by the backend, is injured and is at the center of the STRAPI.

# STRAPI

Simply put, STRAPI is a service that is only responsible for the backend part of CMS such as WordPress. Whether you develop the front end with react.js or vue.js, you can do it yourself, and the back end is to send and receive data with RESTful or GraphQL provided by STRAPI. The content thus obtained can be managed by STRAPI. Please refer to the link below for a detailed description.

STRAPI is responsible for the backend that is essential for front-end developers

Serving STRAPI V4 in the Synology Docker

There is a function to use the docker when viewed in the synopsis.
You can use this docker to service STRAPI. But there's one small problem. Until last year, STRAPI made a docker image and uploaded it to the docker hub, so it was easy to use, but from now on, they will not make a docker image. Therefore, you can only install STRAPI of the only version (STRAPI V3) that you want to use after receiving STRAPI from Registry (=Docker Hub) of Synology Docker.

So I decided to make a docker image and post it on the synopsis for service.
I share the information I learned while shoveling for three days to create a Docker image. For your information, I'm a beginner who doesn't know much about dockers. I didn't fully understand it because I solved it while Googleing, so please point it out if there is anything wrong.

Create Docker Image

First, we will proceed under the assumption that there is a docker installed. For Windows or Mac, you can install the docker desktop below.

Docker Desktop Shortcut

Creating a Dockerfile

In order to create a Docker Image, you must first create a content on how to create it, and that is the Dockerfile file. Images are created in the order of what is written here.

########################
## Dockerfile file ##
########################

# # BASE OS
# Create the default OS for the image as what you want to do.
# It's hard to write here, but... A conclusion is
# Install the Alpine Linux OS with node.js 14 version as the default OS and set the port to 1337.
ARG NODE_VERSION=14
FROM node:${NODE_VERSION}-alpine AS base-alpine
EXPOSE 1337

FROM base-alpine

# Alpine Linux is the lightest Linux of all Linux features and is an OS that has been removed.
# So basically, it's convenient to install a minimum program to use.
# apk update : updates installed programs to the latest version
# apk add~~ :~~~~~~~~~~~~~~~~~~~~~~~~~>
RUN apk update && apk add build-base gcc autoconf automake zlib-dev libpng-dev nasm bash vips-dev

# ARG is a variable used only within a Dockerfile
# Create the STRAPI_VERSION to install. Latest means that we will install the latest version at this point.
ARG STRAPI_VERSION=latest

# First, install the specified version of STRAPI globally on alpine Linux.
# This eliminates the need to install STRAPI on the local computer.
RUN yarn global add @strapi/strapi@${STRAPI_VERSION}

# You will install the STRAPI source in the /srv/app directory.
# Create the /srv/app directory and grant permissions to the first user to free up the directory.
# Now this folder is mine.
RUN mkdir -p /srv/app && chown 1000:1000 -R /srv/app

# Set the Actions folder. Project files will now be stored and executed in this folder.
WORKDIR /srv/app

# Set the volume to send and receive data to and from the local computer. The contents of this folder will now be shared equally among local folders.
VOLUME /srv/app

# # docker-entrypoint.Copy docker-entrypoint.sh to /usr/local/bin/ on the docker to run sh.
# The contents written in this file will be executed and the project file will be created.
COPY docker-entrypoint.sh /usr/local/bin/

# # docker-entrypoint.Release sh's permissions.
# Grant permissions to prevent problems when creating files or folders.
RUN chmod 777 /usr/local/bin/docker-entrypoint.sh && ln -s /usr/local/bin/docker-entrypoint.sh

# Runs the docker-entrypoint.sh file that was moved the first time the container was run via the docker image.
ENTRYPOINT ["docker-entrypoint.sh"]

# The command is executed the first time the container is run via the docker image.
CMD ["strapi"]

The following docker-entrypoint.sh file will be executed by ENTRYPOINT: This file must also be located in the same space as the Dockerfile file.

#################################
## ## docker-entrypoint.sh 파일 ##
#################################

#!/bin/sh
set -ea

if [ "$*" = "strapi" ]; then
  if [ ! -f "package.json" ]; then
    DATABASE_CLIENT=${DATABASE_CLIENT:-sqlite}
    EXTRA_ARGS=${EXTRA_ARGS}
    The echo "Strapi $(strapi version) version is in use."
    echo "There are currently no projects in the /srv/app folder. Create a new Strapi project..."

    DOCKER=true strapi new . --no-run \
    --dbclient=$DATABASE_CLIENT \
    --dbhost=$DATABASE_HOST \
    --dbport=$DATABASE_PORT \
    --dbname=$DATABASE_NAME \
    --dbusername=$DATABASE_USERNAME \
    --dbpassword=$DATABASE_PASSWORD \
    --dbssl=$DATABASE_SSL \
    $EXTRA_ARGS
  elif [ ! -d "node_modules" ] || [ ! "$(ls -qAL node_modules 2>/dev/null)" ]; then
    if [ -f "yarn.lock" ]; then
    echo "Node modules are not installed. Installing module using Yarn..."
    yarn install --prod --silent
    yarn build
    else
    echo "Node modules are not installed. Installing module using npm..."
    npm install --only=prod --silent
    npm run build
    fi
  fi

  if [ "$NODE_ENV" = "production" ]; then
    STRAPI_MODE="start"
  elif [ "$NODE_ENV" = "development" ]; then
    STRAPI_MODE="develop"
  fi
  Echo "Launch the App. (with ${STRAPI_MODE:-develop})..."
  exec strapi "${STRAPI_MODE:-develop}"
else
  exec "$@"
fi

Creating a Docker Image

Now, all the preparations are done. Now, let's create a Docker image. The command to create a docker image is as follows. There are many different options, but I only applied the options below.

Docker build -t <image name to be created>:<tag name> <Dockerfile location>

# Sample
docker build -t njo2-strapi-4.5.3:1.0 .

the last of the .Don't forget to paste . You can specify the location where Dockerfile is located, but usually the command is executed from the location where Dockerfile is located, indicating the current location.Put on it.
This command does not seem to change anything. It is not downloaded as a separate file. If you look at Docker's image list on the Docker command or on the Docker desktop, you can see that the results have been generated.

  1. On Docker Desktop, run the docker images ls command in the CMD window from the left image menu...
  2. A list of the current images will appear.

Download Docker Image to a Local File

To add an image to the Synology Docker, you must download the Docker image first. The downloaded file is a compressed file.Downloaded to tar Enter the command below to create a tar compressed file called njo2-strapi-4.5.3.tar.

docker save -o <Docker image compression file name to download> <Docker image to create>

# Sample
docker save -o njo2-strapi-4.5.3.tar njo2-strapi-4.5.3

Now upload this compressed file to the synopsis as it is.

Applying Docker Images to a Synology NAS

It is recommended that you first verify that the container is created and executed successfully with the docker desktop on your local computer. Once determined to be a normal image, now upload the docker image to the shared folder on the Synology NAS.

Uploading an Image to a Synology

It doesn't matter where you are. I created and uploaded a folder called \_IMAGES.

Registering an Image with a Synology Docker

Now register this image with the Synology Docker. Run the Docker program in the scenario.

  1. In the Docker app, select Image from the left menu.
  2. Select Add from the top menu.
  3. From File, select Add.

Select the image file from the uploaded folder to add the image. It's over 1GB, so it takes some time to add it.(approximately 2 to 5 minutes?) There are times when the addition fails, but it can go up after several more attempts.

The image is then registered as shown above.

Running the Strapi Docker Container

Now, you can run the container with the uploaded image, but before that, you need to install the DB. If you do not install a separate DB, you will automatically use the built-in lightweight sqlite, which is not a powerful DB. We recommend that you install and use postgreSQL whenever possible.

Please refer to the posting below for installation instructions.

Install STRAPI with Docker on the Synology NAS

There are parts of the above posting that run the Strapi container, but the contents below are improved, so please refer to the following.
Double-click Strapi image added from the image above to begin container installation.

Select a network first. For networks, select the same network as postgreSQL.

  1. You can usually choose bridge.
  2. Click the Next button.

  1. Set the container name first.
  2. Select Advanced Settings.

  1. Select the Environment tab and enter the environment variable.
  2. Click the Add button 7 times to create 7 input spaces.
  3. Enter the default 7 environment variable information.

The environmental information that needs to be set is as follows. Enter seven important variables and four additional variables.

setting value information setting environment variable

Environment Variables Values Description
Whether to develop NODE_ENV development / production.
DATABASE_CLIENT postgres Create a db type to use.
Creates the DB name set in DATABASE_NAME strapi strapi_postgres.
DATABASE_HOST 192.168.0.10 Create the IP address of the Synology NAS.
Create the port number set in DATABASE_PORT 15432 strapi_postgres.
Create the User set in DATABASE_USERNAME strapi strapi_postgres.
Create the password you set in DATABASE_PASSWORD strapi strapi_postgres.

Below are options

Environment Variables Values Description
Create DATABASE_SSL SSL Security
JWT_SECRET User Rights Plug Citation Password used to sign JWT.
ADMIN_JWT_SECRET Password used to sign JWT for Administrator Panel.
APP_KEYS Secret key used to sign session cookies.

  1. Click the Link tab.
  2. Click the Add button.
  3. Select postgreSQL from the container name. PostgreSQL must be installed in advance to be listed.
  4. Enter any alias.

Now exit the advanced settings and click the Next button.

Next, set the port settings.

  1. Local ports can be created to actually serve. The port must be opened by a firewall and can be accessed through that port. You can enter any number.
  2. You need to create a container port, and this port number can be 1337 port unless it is special. (It needs to be the same as EXPOSE 1337 in the docker file setting.)

Finally, you can set the volume. This volume matches a folder on the local computer (shared folder in synopsis) with a specific folder on the docker image. So if you add a file here, it's synchronized to the other folder as well.

  1. Click the Add File or Add Folder button (Strapi only needs to add folders)
  2. For File/Folder, you can select the specific folder you want from Synology Nas.
  3. The mount path can be created by creating a docker image path, unless otherwise, you can create /srv/app. (As long as it is the same as VOLUME/srv/app in the dockerFile setting.)

This is the summary information that will eventually be generated.

  1. Click the Finish button to create and run the container immediately.

Open Firewall

Once the installation is complete, the Synology NAS must open the firewall. Failure to open may cause the container to die immediately upon initial installation.

Firewall is specified on the Security tab in Control Panel.

  1. Select the Control Panel icon.
  2. Select the Security tab.
  3. Select the Firewall tab.
  4. Click the Edit Rule button.

You can turn off the firewall for the above three Strapi-related programs. (The program name may vary.)

Try connecting

If you connect and see the screen above, 90% of the installation is complete. The rest of the problems can be solved by addressing the errors below.

Possible Errors

Initial container execution error

Situation

Running the container for the first time after the above setting can cause the container to die immediately.
The reason for this is that the dependency file is installed in the node_modules folder by package.json when it first runs, which is blocked by the firewall in the scenario and cannot be installed, resulting in an error.

Workaround

The solution is simple. If you release and install the firewall during the initial installation, the installation proceeds well. However, after the installation, you must re-enable the firewall. If you want to install the plug-in in the future, you must open the firewall again and close it again when the installation is complete. (Please check the explanation above.)

xxx파일 : no such file or directory

docker-entrypoint.sh : no such file or directory 또는 package.json : no such file or directory

Situation

When you create Dockerfile and run it as a container, you may encounter an error similar to the above. No matter how much I look at it, there is nothing wrong, but the above error occurs. I lost almost two days because of this.
For many different reasons, my problem was the CRLF problem. CRLF, LF is a new line type with invisible codes (\r\n) for CRLF, and (\n) for LF. This is a problem that occurs because each OS, such as Linux and Windows, has a different type of basic line change.

Workaround

If the solution was CRLF, change it to LF, and if it was LF, change the format of the line change to CRLF.
If you use VSCode, you can modify it as below.

  1. Click CRLF or LF at the bottom right.
  2. In the center of the top, select one of the two menus.

Strapi: Warning an error occurred while requesting the API

Situation

This part is installed normally and comes up to the initial screen, but when I access the actual administrator screen (https://localhost/admin), I sometimes get an error screen called Strapi: Warning an error while requesting the API.

Workaround

The above problem is usually solved by building it before service. ( yarn build )
In the code above, the solution has already been applied, so it takes more time to build when loading for the first time.

# ...
  if [ -f "yarn.lock" ]; then
    echo "Node modules are not installed. Installing module using Yarn..."
    yarn install --prod --silent
    Yarn build # Added build
  else
    echo "Node modules are not installed. Installing module using npm..."
    npm install --only=prod --silent
    npm run build # added build
  fi
# ...

oci runtime exec failed "/bin/bash"

Situation

The above problem is not actually an error. However, the problem is caused by the lack of bash in the OS.
This is because alpineLinux, which is used as the base OS for docker images, has removed most of the features to lighten the size, so there are features that are not available instead of small capacity. Among them, this phenomenon occurs because the bash program is also taken away. Instead of bash, sh is available by default.

Workaround

The above issue is the code to install alpine from dockerFile followed by the code below.

RUN apk update && apk add bash

I have applied it to dockerFile above.

댓글

이 블로그의 인기 게시물

CSS에서 ellipsis('...')를 처리하는 방법

이번에 ellipsis에 대해 정리해 보도록 하겠습니다. 보통 게시판 리스트의 제목부분이 길어질 경우 php나 jsp등의 프로그램단에서 일정 글자수 이상이 되는 것에 대해 '...'으로 마무리 하는 경우가 많은데요.. 이것을 프로그램이 아닌 CSS만 가지고도 처리할 수 가 있습니다. 한줄라인 글자수 제한 한줄 라인 글자수 를 제한하는 방법은 아래와 같습니다. <div class="txt_line">통영의 신흥보물 강구안의 동쪽벼랑인 동피랑의 벽화마을을 다녀왔다</div> .txt_line { width:70px; padding:0 5px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } Block레벨 테그에서만 적용됨. overflow:hidden : 넓이가 70px를 넒어서는 내용에 대해서는 보이지 않게 처리함 text-overflow:ellipsis : 글자가 넓이 70px를 넘을 경우 생략부호를 표시함 white-space:nowrap : 공백문자가 있는 경우 줄바꿈하지 않고 한줄로 나오게 처리함 (\A로 줄바꿈가능) 멀티라인 글자수 제한 멀티라인에 대해서 글자수를 제한하는 방법은 아래와 같습니다. <p class="txt_post">통영의 신흥보물 강구안의 동쪽벼랑인 동피랑의 벽화마을을 다녀왔다.&nbsp; 비도 추적추적 내리고 일정상 늦으막해서 그런지 사람이 많지는 않았다. 덕분에 보통때는 한참을 기다려야 겨우 날개달린 사진을 찍을 수 있었을 텐데, 이번에는 바로 천사날개를 달고 사진을 찍을 수 있는 행운까지 얻었다. 이번이 동피랑 벽화마을 방문 3번째인데 예전에 왔을때에 비해서 벽화가 많이 바뀌어 있었다</p> .txt_post { overflow: hidden; text-ove...

Google 스프레드시트로 구글캘린더에 일정 연동하는 방법

저는 구글 제품을 많이 사용하는 편입니다. 제 주력 캘린더도 Google 캘린더 고요. 이번에 모임의 임원을 맡게 되면서 회원들의 생일을 캘린더에 등록해야 할 일이 생겼어요. 그냥 하나하나 등록을 하는 도중 "내가 지금 뭐하고 있나.." 라는 자괴감이 들기 시작했어요. 구글 시트에 있는 날짜 정보(생일)을 한 번에 쉽게 일괄 등록할 수는 없을까라는 생각이 뇌리를 스쳤습니다. 그래서 찾아봤더니.. 약간의 매크로 프로그램을 작성하면 가능할 것 같더라고요. 그래서 열심히 개발을 해봤습니다. 1시간이면 등록할 것을 8시간 걸려서 프로그램을 짜 봤어요. 결과적으로는 더 비효율적이었네요. ㅠㅠ 그러나... 나에게는 비효율 적이었지만 이코드를 공개하면 다른 사람에게는 큰 도움이 될 수 있겠구나 생각을 하고 코드를 공개해 보려고 합니다. 준비물 준비물은 Google 스프레드시트, Google 캘린더만 있으면 돼요. 당연히 무료고요. Google 캘린더 먼저 Google 캘린더를 만들거나 사용하고 있는 캘린더를 준비합니다. 적용하기 원하는 캘린더의 우측의 ... 를 클릭하고 설정 및 공유 를 선택합니다. 캘린더 ID를 잘 기억해 놓습니다. 나중에 이 ID를 활용할 예정입니다. Google 스프레드시트 회원생일 스프래드시트 공유 Google 스프레드시트로 명단과 생일을 작성합니다. ▲ 위와 같이 작성을 하면 되고 중요한 사항은.. 생년월일 이 구글 시트의 날짜 형식에 맞아야 합니다. 그리고 갤린더등록 , 캘린더상태 의 항목은 필수로 있어야 합니다. 캘린더등록 : 캘린더에 등록할지 제거할지를 표시 (ADD / DEL) 캘린더상태 : 현재 캘린더에 해당 항목이 적용되었는지 확인 (Y / ' ') 매크로 프로그램 작성하기 기본적인 준비는 끝났습니다. 이제부터 Apps Script를 제작하고 트리거를 등록하면 됩니다. Apps Script 작성하기 Apps Script 는 구글 제품에 대...

Google캘린더(달력)에 대한민국 휴일 표시하기

구글 캘린더에 대한민국 휴일을 표시하는 설정에 대해서 소개합니다. 네이버 달력이라면 그냥 기본으로 나오겠지만 구글캘린더의 경우는 별도의 설정을 해 주어야 합니다. 휴일의 표시는 각 나라의 휴일을 구글에서 미리 작성해 놓은 것을 내 캘린더에 불러와 적용하는 방식으로 되어 있습니다. 대한민국 공유일 표시하기 먼저 설정화면으로 이동합니다. 캘린더 화면의 우측상단의 설정 아이콘을 클릭합니다. 메뉴 중 설정 을 클릭합니다. 설정화면 중 좌측 메뉴에서 캘린더 추가 메뉴를 선택합니다. 관심분야와 관련된 캘린더를 선택합니다. 지역 공휴일의 모두 둘러보기 를 선택하면 각나라의 휴일을 선택할 수 있습니다. 우리는 대한민국의 휴일 을 선택합니다. 캘린더에서 공휴일 보기 대한민국 휴일에 대한 설정을 했다면 이제 보기 좋게 표시하면 됩니다. 설정을 정상적으로 했다면 좌측메뉴에 대한민국의 휴일 이라는 캘린더가 보입니다. 캘린더명의 우측끝에 더보기 아이콘 을 선택합니다. 색상을 빨간색으로 선택합니다. (보통 공휴일은 빨간색이므로.. ㅎ) 그러면 캘린더에 휴일의 명칭이 빨간색 으로 표시되게 됩니다. 감사합니다.