Strapi + Next.JS + docker-compose: Is static generation impossible during build? - docker-compose

When I try to build my Next.JS application, which has a getStaticProps() function to get data from Strapi, the fetch fails. It fails because it is unable to resolve the alias for the Strapi container while building. Is there a way around this? Here's some info. Let me know if more info would be helpful:
Docker version 20.10.14
docker-compose version 1.29.2
Next.JS version 12.1.0
Node.JS version v17.6.0
In my pages/index.tsx file, I have the following:
export async function getStaticProps() {
let data: PageData = null;
try {
const response = await axios.get(
`${process.env.STRAPI_BACKEND_URL}/api/pages?filters[slug]=strapi-sample-homepage-content`,
{
headers: {
Accept: "application/json",
},
timeout: 500,
}
);
data = response.data.data[0].attributes || null;
} catch (error) {
console.log(error);
}
return {
props: {
data,
},
revalidate: 60,
};
}
This is what Next.JS wants to generate statically while building, and it's unable to because it cannot resolve the location of the Strapi container during build.
docker-compose.yml:
version: '3.8'
services:
db-strapi:
image: 'location/of/image'
container_name: db-strapi
restart: always
volumes:
- db-strapi:/var/lib/postgresql/data
environment:
- POSTGRES_DB=${STRAPI_DB_NAME}
- POSTGRES_PASSWORD=${STRAPI_DB_PW}
- POSTGRES_SCHEMA=${STRAPI_DB_SCHEMA}
- POSTGRES_USER=${STRAPI_DB_USER}
strapi-backend:
image: 'location/of/image'
container_name: strapi-backend
environment:
- ADMIN_JWT_SECRET=${STRAPI_ADMIN_JWT_SECRET}
- API_TOKEN_SALT=${STRAPI_API_TOKEN_SALT}
- APP_KEYS=${STRAPI_APP_KEYS}
- DATABASE_CLIENT=${STRAPI_DB_CLIENT}
- DATABASE_HOST=${STRAPI_DB_HOST}
- DATABASE_NAME=${STRAPI_DB_NAME}
- DATABASE_PASSWORD=${STRAPI_DB_PW}
- DATABASE_PORT=${STRAPI_DB_PORT}
- DATABASE_SCHEMA=${STRAPI_DB_SCHEMA}
- DATABASE_USERNAME=${STRAPI_DB_USER}
- JWT_SECRET=${STRAPI_JWT_SECRET}
- NODE_ENV=${STRAPI_NODE_ENV}
ports:
- 1337:1337
depends_on:
- "db-strapi"
db-nextjs:
image: 'location/of/image'
container_name: db-nextjs
restart: always
volumes:
- db-nextjs:/var/lib/postgresql/data
environment:
- POSTGRES_DB=${NEXTJS_DB_NAME}
- POSTGRES_PASSWORD=${NEXTJS_DB_PW}
- POSTGRES_SCHEMA=${NEXTJS_DB_SCHEMA}
- POSTGRES_USER=${NEXTJS_DB_USER}
nextjs-app:
image: 'location/of/image'
container_name: nextjs-app
environment:
- STRAPI_BACKEND_URL
- NEXTJS_DB_URL
- SECRET_COOKIE_PASSWORD
- NEXT_TELEMETRY_DISABLED=1
restart: always
depends_on:
- "db-nextjs"
nginx:
image: 'location/of/image'
container_name: nginx
environment:
- NGINX_SERVER_NAME
- NGINX_STRAPI_SERVER_NAME=${STRAPI_BACKEND_HOST}
- RESOLVER
- ENVIRONMENT
- NGINX_CERTIFICATE_NAME
- NEXTJS_HOST
- STRAPI_HOST
ports:
- 80:80
- 443:443
restart: always
depends_on:
- "nextjs-app"
- "strapi-backend"
volumes:
- certbot_certificates:/etc/letsencrypt
- certbot_challenges:/usr/share/nginx/html/.well-known/acme-challenge
volumes:
db-strapi:
db-nextjs:
certbot_certificates:
certbot_challenges:
In my .env.local file:
STRAPI_BACKEND_HOST="strapi-backend"
STRAPI_BACKEND_PORT="1337"
STRAPI_BACKEND_URL="http://${STRAPI_BACKEND_HOST}:${STRAPI_BACKEND_PORT}"
When I build, I have the following output:
info - Generating static pages (0/7)
info - Generating static pages (1/7)
info - Generating static pages (3/7)
info - Generating static pages (5/7)
Error: getaddrinfo ENOTFOUND strapi-backend
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:72:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'strapi-backend',
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 500,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: { Accept: 'application/json', 'User-Agent': 'axios/0.24.0' },
method: 'get',
url: 'http://strapi-backend:1337/api/pages?filters[slug]=strapi-sample-homepage-content',
data: undefined
},
To me, it seems there's no way to resolve this, because Next.js doesn't seem to be on the docker network yet during build. Are there any solutions?

It seems that Docker's hostname resolution does not work during build time. On Mac, you can try STRAPI_BACKEND_HOST = "host.docker.internal". On Linux, using host networking during build worked for me:
nextjs-app:
build:
network: "host"
# ...
network_mode: "host"
This way, you can use STRAPI_BACKEND_HOST = localhost.

Related

Asp.net Core : Docker-Compose.yml configuration vs Docker Section configuration in the LaunchSettings.json

I have an Asp.net Core application with Docker-Compose.yml configuration and Docker Section configuration in the LaunchSettings.json
Connection string is configured like mentioned below in the Docker-Compose.yml
PersistenceAccess__ConnectionString= Server=db;Port=5432;Database=DemoDatabase;User Id=postgres;Password=postgres;
version: '3.4'
services:
Demo.api:
image: ${DOCKER_REGISTRY-}demoapi
build:
context: .
dockerfile: Sources/Code/Demo.Api/Dockerfile
environment:
- ASPNETCORE_ENVIRONMENT=Development
- PersistenceAccess__ConnectionString= Server=db;Port=5432;Database=DemoDatabase;User Id=postgres;Password=postgres;
ports:
- '8081:80'
depends_on:
- db
db:
image: postgres
restart: always
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
logging:
options:
max-size: 10m
max-file: "3"
ports:
- '5438:5432'
volumes:
- ./postgres-data:/var/lib/postgresql/data
# copy the sql script to create tables
- ./sql/create_tables.sql:/docker-entrypoint-initdb.d/create_tables.sql
# copy the sql script to fill tables
- ./sql/fill_tables.sql:/docker-entrypoint-initdb.d/fill_tables.sql
Same Connection string is configured in the LaunchSettings.json like mentioned below
"PersistenceAccess__ConnectionString": "Server=host.docker.internal;Port=5432;Database=DemoDatabaseNew;User Id=postgres;Password=postgres;"
{
"iisSettings": {
..
},
"profiles": {
"IIS Express": {
...
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
"environmentVariables": {
"PersistenceAccess__ConnectionString": "Server=host.docker.internal;Port=5432;Database=DemoDatabaseNew;User Id=postgres;Password=postgres;"
},
"DockerfileRunArguments": "--add-host host.docker.internal:host-gateway",
"publishAllPorts": true,
"useSSL": false
}
}
}
Which configuration will be used while I run the application using
docker-compose -f docker-compose.yml up
Does the above command create a Database? If so, when it will create the database and what would be the name of the database? Also, when it would create the tables and seed the data?
Please suggest.

How to fix "Error: getaddrinfo ENOTFOUND redis" on docker?

I am using Redis using NestJS and I see following error. I am going through different articles like here and looks like I am following the same but still getting this error.
Steps:
I used docker compose up command
Made sure that host in redis.module.ts is same as service name in docker-compose.yml which is redis.
What am I missing here?
Error:
Error: getaddrinfo ENOTFOUND redis
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26)
Code:
redis.module.ts
import { CacheModule, Module } from '#nestjs/common';
import { ConfigModule, ConfigService } from '#nestjs/config';
import { RedisService } from './redis.service';
import * as redisStore from 'cache-manager-redis-store';
import { envVariables } from '../env.variables';
#Module({
imports: [
CacheModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
store: redisStore,
host: process.env.REDIS_HOST,
port: configService.get('REDIS_PORT'),
ttl: configService.get('CACHE_TTL'),
max: configService.get('MAX_ITEM_IN_CACHE'),
}),
}),
],
providers: [RedisService],
exports: [RedisService],
})
export class RedisModule {}
.env
#REDIS
REDIS_HOST=redis
docker-compose.yml
version: "3.8"
services:
partnersusers:
image: partnersusers
build:
context: .
dockerfile: ./Dockerfile
environment:
- RUN_ENV=dev
- NODE_ENV=development
ports:
- "4000:4000"
networks:
- default
redis:
image: 'redis:alpine'
ports:
- "6379:4000"
networks:
default:
driver: bridge
Error in Docker:
I'm not an expert, but I notice a couple of things on your docker-compose.yml file.
First your redis service is missing the network assignation:
networks:
- default
Without this, redis-commander won't be able to find it as it's not on the same network.
Second redis by default runs on port: 6379 if you want it to run on port 4000 I believe you will need to specify an env var for it.
Or here maybe you just confused the order of the port matching which should've been: 4000:6379 (host_port:container_port).
this is my working docker-compose.yml for reference:
---
version: '3.8'
services:
...
redis:
image: redis
container_name: redis
hostname: redis
environment:
- ALLOW_EMPTY_PASSWORD=yes
ports:
- '6379:6379'
networks:
- my-net
redis-commander:
depends_on:
- redis
container_name: redis-commander
hostname: redis-commander
image: rediscommander/redis-commander:latest
restart: always
environment:
- REDIS_HOSTS=local:redis:6379 # note: this has to be the port the redis container exposes.
ports:
- "8081:8081"
networks:
- my-net
networks:
my-net:
Hope this helps :)

How to get Dapr Service to Service Invocation to work when running under docker-compose?

I am receiving the following error when trying to call a service using Dapr SDK.
System.Net.Http.HttpRequestException: Connection refused (127.0.0.1:3500)
---> System.Net.Sockets.SocketException (111): Connection refused
Here is my docker-compose settings of the service I am trying to call:
quest-service:
image: ${DOCKER_REGISTRY-gamification}/quest-service:${TAG:-latest}
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://0.0.0.0:80
- SeqServerUrl=http://seq
build:
context: .
dockerfile: Services/LW.Gamification.QuestService/Dockerfile
ports:
- "5110:80"
- "50010:50001"
quest-service-dapr:
image: "daprio/daprd:latest"
command: ["./daprd",
"-app-id", "Quest-Service",
"-app-port", "80",
"-components-path", "/Components",
"-config", "/Configuration/config.yaml"
]
volumes:
- "./Dapr/Components/:/Components"
- "./Dapr/Configuration/:/Configuration"
depends_on:
- quest-service
network_mode: "service:quest-service"
And the settings for the caller:
player-service:
image: ${DOCKER_REGISTRY-gamification}/player-service:${TAG:-latest}
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://0.0.0.0:80
- SeqServerUrl=http://seq
build:
context: .
dockerfile: Services/LW.Gamificaiton.PlayerService/Dockerfile
ports:
- "5109:80"
- "50009:50001"
player-service-dapr:
image: "daprio/daprd:latest"
command: ["./daprd",
"-app-id", "Player-Service",
"-app-port", "80",
"-components-path", "/Components",
"-config", "/Configuration/config.yaml"
]
volumes:
- "./Dapr/Components/:/Components"
- "./Dapr/Configuration/:/Configuration"
depends_on:
- player-service
network_mode: "service:player-service"
And here is the code that is failing to work:
// demo service to service call
var httpClient = DaprClient.CreateInvokeHttpClient("Quest-Service");
var requestUri = $"api/v1/Quest";
var result = await httpClient.GetFromJsonAsync<IEnumerable<string>>(requestUri);
Note: Messaging is working fine. :-)
I am new to Dapr so I must be doing something silly wrong, maybe something to do with ports.. I just don't know!
From following this question :Dapr Client Docker Compose Issue
I managed to get this partly working using the following docker-compose config:
services:
placement:
image: "daprio/dapr"
command: ["./placement", "-port", "50000", "-log-level", "debug"]
ports:
- "50000:50000"
quest-service:
image: ${DOCKER_REGISTRY-gamification}/quest-service:${TAG:-latest}
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://0.0.0.0:80
- SeqServerUrl=http://seq
- DAPR_GRPC_PORT=50010
build:
context: .
dockerfile: Services/LW.Gamification.QuestService/Dockerfile
ports:
- "5110:80"
- "50010:50010"
depends_on:
- placement
- rabbitmq
- redis
- seq
- zipkin
quest-service-dapr:
image: "daprio/daprd:latest"
command: ["./daprd",
"-app-id", "Quest-Service",
"-app-port", "80",
"-placement-host-address", "placement:50000",
"-dapr-grpc-port", "50010",
"-components-path", "/Components",
"-config", "/Configuration/config.yaml"
]
volumes:
- "./Dapr/Components/:/Components"
- "./Dapr/Configuration/:/Configuration"
depends_on:
- quest-service
network_mode: "service:quest-service"
generatetraffic:
image: ${DOCKER_REGISTRY-gamification}/generatetraffic:${TAG:-latest}
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://0.0.0.0:80
- SeqServerUrl=http://seq
- DAPR_GRPC_PORT=50017
build:
context: .
dockerfile: Services/LW.Gamification.GenerateTraffic/Dockerfile
ports:
- "5117:80"
- "50017:50017"
depends_on:
- placement
- rabbitmq
- redis
- seq
- zipkin
generatetraffic-dapr:
image: "daprio/daprd:latest"
command: ["./daprd",
"-app-id", "Generate-Traffic",
"-app-port", "80",
"-placement-host-address", "placement:50000",
"-dapr-grpc-port", "50017",
"-components-path", "/Components",
"-config", "/Configuration/config.yaml"
]
volumes:
- "./Dapr/Components/:/Components"
- "./Dapr/Configuration/:/Configuration"
depends_on:
- generatetraffic
network_mode: "service:generatetraffic"
However I still have issues with some of the documented APIs not working!.
var httpClient = DaprClient.CreateInvokeHttpClient("Quest-Service");
var requestUri = $"api/v1/Quest";
var result = await httpClient.GetAsync(requestUri);
Still fails?

Knex & postgres connection error - error: role "admin" does not exist

I am trying to connect to postgres db image using knex. But I am getting error:-
error: role "admin" does not exist
My knexfile is ass below:
module.exports = {
development: {
debug: true,
client: 'pg',
connection: {
database: process.env.POSTGRES_DB,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD
},
migrations: {
directory: __dirname + '/src/migrations'
},
seeds: {
directory: __dirname + '/src/seeds'
}
}
};
And my docker-compose file is:-
version: '3.1'
services:
db:
image: postgres
restart: always
volumes:
- ./docker-data/db-data:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRESS_USER: ${POSTGRES_USER}
POSTGRESS_DB: ${POSTGRES_DB}
ports:
- 5432:5432
pgadmin:
depends_on:
- db
image: dpage/pgadmin4
restart: always
environment:
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD}
volumes:
- ./docker-data/pgadmin-data:/root/.pgadmin
ports:
- 8080:80
Environment variables are straight forward
POSTGRES_USER=admin
POSTGRES_PASSWORD=admin
POSTGRES_DB=configs
PGADMIN_DEFAULT_EMAIL=admin#admin.com
PGADMIN_DEFAULT_PASSWORD=admin
Packages details:
"knex": "^0.21.1",
"pg": "^8.3.0"
I ran command docker-compose up and on completion i created migrations and post that i ran npx knex migrate:latest. This is resulting in error
error: role "admin" does not exist
at Parser.parseErrorMessage (/Users/test/packages/config-server/node_modules/pg-protocol/dist/parser.js:278:15)
I am not able to debug and fix. Please help.

SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:5432 when using docker to use sequelize

I'm getting the following error when dockerizing a node postgres database using sequelize as an orm backend
Unhandled rejection SequelizeConnectionRefusedError: connect
ECONNREFUSED 127.0.0.1:5432 app_1 | at
connection.connect.err
(/home/app/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:170:24)
These lines of code seems to be the culprit, docker should not be connecting these credentials as this is for my local.
if (process.env.NODE_ENV === "production") {
var sequelize = new Sequelize(process.env.DATABASE_URL);
} else {
// docker is looking at these credentials..... when it should not
var sequelize = new Sequelize("elifullstack", "eli", "", {
host: "127.0.0.1",
dialect: "postgres",
pool: {
max: 100,
min: 0,
idle: 200000,
// #note https://github.com/sequelize/sequelize/issues/8133#issuecomment-359993057
acquire: 1000000,
},
});
}
docker-compose.yml
# docker-compose.yml
version: "3"
services:
app:
build: ./server
depends_on:
- database
ports:
- 5000:5000
environment:
# database refers to the database server at the bottom called "database"
- PSQL_HOST=database
- PSQL_USER=postgres
- PORT=5000
- PSQL_NAME=elitypescript
command: npm run server
client:
build: ./client
image: react_client
links:
- app
working_dir: /home/node/app/client
volumes:
- ./:/home/node/app
ports:
- 3001:3001
command: npm run start
env_file:
- ./client/.env
database:
image: postgres:9.6.8-alpine
volumes:
- database:/var/lib/postgresql/data
ports:
- 3030:5432
volumes:
database:
./server/dockerFile
FROM node:10.6.0
COPY . /home/app
WORKDIR /home/app
COPY package.json ./
RUN npm install
EXPOSE 5000
I looked at other similar questions like the following, but it ultimately did not help solve the issue.
Docker - SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306
SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306
I solved it...
What i did was change this
host: "127.0.0.1",
to this
let sequelize;
if (process.env.NODE_ENV === "production") {
sequelize = new Sequelize(process.env.DATABASE_URL);
} else {
sequelize = new Sequelize(
process.env.POSTGRES_DB || "elitypescript",
process.env.POSTGRES_USER || "eli",
"",
{
host: process.env.PSQL_HOST || "localhost",
dialect: "postgres",
pool: {
max: 100,
min: 0,
idle: 200000,
// #note https://github.com/sequelize/sequelize/issues/8133#issuecomment-359993057
acquire: 1000000,
},
}
);
}
that way the host would be set to docker environment variable like this
PSQL_HOST: database
and that connects to
database:
image: postgres:9.6.8-alpine
volumes:
- database:/var/lib/postgresql/data
ports:
- 3030:5432
Edit
# docker-compose.yml
version: "3"
services:
app:
build: ./server
depends_on:
- database
ports:
- 5000:5000
environment:
PSQL_HOST: database
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-password}
POSTGRES_USER: ${POSTGRES_USER:-postgres}
POSTGRES_DB: ${POSTGRES_DB:-elitypescript}
command: npm run server
client:
build: ./client
image: react_client
links:
- app
working_dir: /home/node/app/client
volumes:
- ./:/home/node/app
ports:
- 3001:3001
command: npm run start
env_file:
- ./client/.env
database:
image: postgres:9.6.8-alpine
volumes:
- database:/var/lib/postgresql/data
ports:
- 3030:5432
volumes:
database: