Slow Next.js builds on Gitlab CI - next.js

We have a JS-based stack in our application - React with vast majority being a React Admin frontend, built on Next.js server, with Postgres, Prisma and Nexus on backend. I realize it's not a great use case for Next.js (React Admin basically puts entire application in a single "component" (root), so basically I have a giant index.tsx page instead of lots of smaller pages), but we've had quite terrible build times in Gitlab CI and I'd like to know if there's anything I can do about it.
We utilize custom gitlab-runners deployed on the company Kubernetes cluster. Our build job essentially looks like:
- docker login
- CACHE_IMAGE_NAME="$CI_REGISTRY_IMAGE/$CI_COMMIT_REF_SLUG:latest"
- SHA_IMAGE_NAME="$CI_REGISTRY_IMAGE/$CI_COMMIT_SHORT_SHA"
- docker pull $CACHE_IMAGE_NAME || true
- docker build
-t $CACHE_IMAGE_NAME
-t $SHA_IMAGE_NAME
--cache-from=$CACHE_IMAGE_NAME
--build-arg BUILDKIT_INLINE_CACHE=1
- docker push # both tags
And the Dockerfile for that is
FROM node:14-alpine
WORKDIR /app
RUN chown -R node:node /app
USER node
COPY package.json yarn.lock ./
ENV NODE_ENV=production
RUN yarn install --frozen-lockfile --production
COPY . .
# Prisma client generate
RUN npm run generate
ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build
ARG NODE_OPTIONS=--max-old-space-size=4096
ENV NODE_OPTIONS $NODE_OPTIONS
EXPOSE 3000
CMD ["yarn", "start"]
This built image is then deployed with Helm into our K8s with the premise that initial build is slower, but subsequent builds in the pipeline will be faster as they can utilize docker cache. This works fine for npm install (first run takes around 10 minutes to install, subsequent are cached), but next build is where hell breaks loose. The build times are around 10-20 minutes. I recently updated to Next.js 12.0.2 which ships with new Rust-based SWC compiler which is supposed to be up to 5 times faster, and it's actually even slower (16 minutes).
I must be doing something wrong, but can anyone point me in some direction? Unfortunately, React Admin cannot be split across several Next.js pages AFAIK, and rewriting it to not use the framework is not an option either. I've tried doing npm install and next build in the CI and copy that into the image, and store in the Gitlab cache, but that seems to just shift the time spent from installing/building into copying the massive directories in/out cache and into the image. I'd like to try caching the .next directory in between builds, maybe there is some kind of incremental build possible but I'm skeptical to say the least.

Well, there are different things that we can approach for making it faster.
You're using Prisma, but you're generating the client every time that you have a modification in any of the files, preventing the Docker cache to actually take care of that layer. If we take a look into the Prisma documentation, we need to generate the Prisma Client each time that there's a change on the Prisma schema, not in the TS/JS Code.
I will suppose you have your Prisma schematics under the prisma directory, but feel free to adapt my suppositions to the reality of your project:
ENV NODE_ENV=production
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile --production
COPY prisma prisma
RUN npm run generate
You're using a huge image for your final container, which maybe doesn't have a significant impact on the build time, but it definitely has on the final size and the time required to load/download the image. I would recommend to migrate into a multi-stage solution like the following one:
ARG NODE_OPTIONS=--max-old-space-size=4096
FROM node:alpine AS dependencies
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile --production
COPY prisma prisma
RUN npm run generate
FROM node:alpine AS build
WORKDIR /app
COPY . .
COPY --from=dependencies /app/node_modules ./node_modules
ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build
FROM node:alpine
ARG NODE_OPTIONS
ENV NODE_ENV production
ENV NODE_OPTIONS $NODE_OPTIONS
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
WORKDIR /app
COPY --from=build /app/public ./public
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/package.json ./package.json
COPY --chown=nextjs:nodejs --from=build /app/.next ./.next
USER 1001
EXPOSE 3000
CMD ["yarn", "start"]
From another point of view, probably you could improve also the NextJS build by changing some tools and modifying the NextJS configuration. You should use locally the tool https://github.com/stephencookdev/speed-measure-webpack-plugin to analyze which is the culprit of that humongous build-time (which probably is something related to sass) and also take a look into the TerserPlugin and the IgnorePlugin.

Related

What could cause a "TypeError: (0 , d.__decorate) is not a function" of an angular function inside a docker container?

I'm building a web application. The frontend is in angular and the backend in .Net Core.
Currently, I'm doing the following, to build my final docker image:
Build angular app
Copy the built angular files in the wwwroot of asp.net core
Building the asp.net core app
Publishing the asp.net core app
Copying the publish result inside a docker image.
Here is my current dockerfile:
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM node:latest as node
WORKDIR /app
COPY Frontend .
RUN npm install
RUN npm run build
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["Backend/my-project.csproj", "Backend/"]
RUN dotnet restore "Backend/my-project.csproj"
COPY Backend Backend
WORKDIR "/src/Backend"
COPY --from=node /app/dist/app/ /wwwroot/
RUN dotnet build "my-project.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "my-project.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "my-project.dll"]
The whole process finish without errors, but when I'm trying to access to http://localhost/, I get the html, but there is a javascript error:
Uncaught TypeError: (0 , d.__decorate) is not a function
at Object.619 (main.3ba20fe70ead0a4b.js:1:45137)
at r (runtime.834ae414fca175dc.js:1:127)
at Object.1983 (main.3ba20fe70ead0a4b.js:1:45670)
at r (runtime.834ae414fca175dc.js:1:127)
at main.3ba20fe70ead0a4b.js:1:512504
at n (runtime.834ae414fca175dc.js:1:2649)
at main.3ba20fe70ead0a4b.js:1:57
But:
the result of ng serve work
serving with a test server the result of npm build works
Copying the result of npm build to wwwroot of my asp.net core works in debug
Publishing the asp.net core app(with the wwwroot populated) also works
When I try to access to each individual file present in my npm build folder, it seems to be accessible(not sure, because names have this number that is not exactly the same)
If I deleted nodes_modules, packages-lock.json and run npm install and npm run build, it also works
I deleted the angular app, created another one, run the whole docker build, it works.
I tried to change node to the version I'm using on my computer(node 16.14)
Edit
I started to remove everything from my app to see when it starts working again. It appears that once I remove my State(s) of NgxsModule.forFeature([]), it works.
So basically, if I've a module with:
NgxsModule.forFeature([])
It works, but NgxsModule.forFeature([UiState]) doesn't, even if UiState is almost empty:
#State<UiStateModel>({
name: 'ui',
defaults: {
isMenuOpen: true,
},
})
#Injectable()
export class UiState {}
I'm kind of desperate, any idea what could cause this error?
I'm not exactly sure what did the trick, but I finally solved it.
What I did:
I had some ngxs packages that were refered as dev dependencies AND dependencies(with different version), I kept only the one in the dependencies
In my tsconfig.json, I was having a paths specified for "tslib"(to the nodes_modules one). I remember I added it, but I don't remember why, I think at some point I was having a compilation error and I found on SO this solution. I did remove this path for tslib, which is what probably solve the issue.

How to regularly expire or delete docker build cache?

Is there a way to expire the cache of the docker build command without explicitly adding the --no-cache flag?
Let's say I would like to search for package (security) updates at least once per week when building my image in the gitlab ci-cd pipeline. And the rest of the time allow caching to speed up the build.
I was thinking of using an auxiliary artifact that expires after certain time, but this is probably not the most elegant (and certainly not portable) solution.
Example of my docker file:
FROM rocker/r-ver:4.0:
# Apply OS updates
# This will be by default cached
RUN apt-get update && apt-get --yes upgrade
COPY myscript.R ./myscript.R
CMD [ "Rscript", "./myscript.R" ]

Why is webpack encore required only in dev

I'm currently configuring some docker images for a symfony 5 project and trying to deal with the production build. Doing so, I noticed that webpack encore is installed only on dev mode, as advised on this official documentation : https://symfony.com/doc/current/frontend/encore/installation.html :
yarn add #symfony/webpack-encore --dev
However, this doesn't make sense to me, since even in production, we are supposed to build the assets :
yarn encore production
Does anyone have clues about this ?
Thank you
The Symfony docs on How Do I Deploy My Encore Assets? provide two important things to remember when deploying assets:
1) Compile Assets for Production:
$ ./node_modules/.bin/encore production
Now the important part:
But, what server should you run this command on? That depends on how you deploy. For example, you could execute this locally (or on a build server), and use rsync or something else to transfer the generated files to your production server. Or, you could put your files on your production server first (e.g. via git pull) and then run this command on production (ideally, before traffic hits your code). In this case, you’ll need to install Node.js on your production server.
And the second important thing:
2) Only Deploy the Built Assets
The only files that need to be deployed to your production servers are the final, built assets (e.g. the public/build directory). You do not need to install Node.js, deploy webpack.config.js, the node_modules directory or even your source asset files, unless you plan on running encore production on your production machine. Once your assets are built, these are the only thing that need to live on the production server.
Simply put, in the production environment you only need the generated assets (usually /public/build directory content). In a simple scenario when you only need to load compiled Javascript and CSS files the Webpack is not used at runtime.
A possible solution how to deploy a Symfony application & assets
When deploying a Symfony app manually (without CI/CD) the following steps can be performed on the local machine or in a Docker container (assumes Symfony 4/5):
Export the source code from GIT repository with git-archive, e.g.: git archive --prefix=myApp/ HEAD | tar -xC /tmp/¹
Go to exported source code: cd /tmp/myApp
Install Symfony & other PHP vendors (see also the Symfony docs): composer install --no-dev --optimize-autoloader
Install YARN/NPM vendors (they'll be required to generate assets with Webpack): yarn install
Create production assets: yarn build (or yarn encore production)
(Install Symfony assets if needed: bin/console assets:install)
Now the code is ready to rsync it to the production server. You may exclude or delete the /node_modules, /var and even /assets directories and webpack.config.js (probably package.json & yarn.lock won't be needed either -- didn't tested it!) and run e.g.: rsync --archive --compress --delete . <myProductionServer>:<app/target/path/>
Resources on Symfony deployment:
How to Deploy a Symfony Application (Symfony docs)
How Do I Deploy My Encore Assets? (Symfony Frontend FAQ)
Do I Need to Install Node.js on My Production Server? (Symfony Frontend FAQ)
Production Build & Deployment (SymfonyCast)
¹ Untars on the fly the archived GIT repository into the /tmp/myApp directory instead of into a TAR archive. Don't miss the leading / in the --prefix flag! git-archive docs.

How to utilize .ebextension while using CodePipeline

I'm using CodePipeline to deploy whatever is on master branch of the git to Elastic Beanstalk.
I followed this tutorial to extend the default nginx configuration (specifically the max-body-size): https://medium.com/swlh/using-ebextensions-to-extend-nginx-default-configuration-in-aws-elastic-beanstalk-189b844ab6ad
However, because I'm not using the standard eb deploy command, I dont think the CodePipeline flow is going into the .ebextension directory and doing the things its supposed to do.
Is there a way to use code pipeline (so i can have CI/CD from master) as well as utilize the benefits of .ebextension?
Does this work if you use the eb deploy command directly? If yes, then I would try using the pipeline execution history to find a recent artifact to download and test with the eb deploy command.
If CodePipeline's Elastic Beanstalk Job Worker does not play well with ebextensions, I would consider it completely useless to deploy to Elastic Beanstalk.
I believe there is some problem with the ebextensions themselves. You can investigate the execution in these log files to see if something is going wrong during deployment:
/var/log/eb-activity.log
/var/log/eb-commandprocessor.log
/var/log/eb-version-deployment.log
All the config files under .ebextension will be executed based on the order of precedence while deploying on the Elastic Beanstalk. So, it is doesn't matter whether you are using codepipeline or eb deploy, all the file in ebextension directory will be executed. So, you don't have to worry about that.
Be careful about the platform you're using, since “64bit Amazon Linux 2 v5.0.2" instead of .ebextension you have to use .platform.
Create .platform directory instead of .ebextension
Create the subfolders and the proxy.conf file like in this path .platform/nginx/conf.d/proxy.conf
In proxy.conf write what you need, in case of req body size just client_max_body_size 20M;
I resolved the problem. You need include .ebextension folder in your deploy.
I only copy the dist files, then I need include too:
- .ebextensions/**/*
Example:
## Required mapping. Represents the buildspec version. We recommend that you use 0.2.
version: 0.2
phases:
## install: install dependencies you may need for your build
install:
runtime-versions:
nodejs: 12
commands:
- echo Installing Nest...
- npm install -g #nestjs/cli
## pre_build: final commands to execute before build
pre_build:
commands:
- echo Installing source NPM dependencies...
- npm install
## build: actual build commands
build:
commands:
# Build your app
- echo Build started on `date`
- echo Compiling the Node.js code
- npm run build
## Clean up node_modules to keep only production dependencies
# - npm prune --production
## post_build: finishing touches
post_build:
commands:
- echo Build completed on `date`
# Include only the files required for your application to run.
artifacts:
files:
- dist/**/*
- package.json
- node_modules/**/*
- .ebextensions/**/*
Ande the config file /.ebextensions/.node-settings.config:
option_settings:
aws:elasticbeanstalk:container:nodejs:
NodeCommand: "npm run start:prod"

meteor bundled application redirects to ssl

My meteor project gets bundled with a script and run with forever. Until now, the process used to work fine but for my last project it does not work.
I setup a clean server with no httpd process running to be sure there is no interference.
there are no errors but when I go to my application on http://dev.sertal.ch:4020 I get redirected to https://dev.sertal.ch
This is the bundle script:
#!/bin/bash
cd /root/projects/tablet-reporting/app
git pull
rm -Rf /opt/sertal/tablet-reporting-test
rm -f /opt/sertal/tablet-reporting-test.tgz
meteor bundle /opt/sertal/tablet-reporting-test.tgz
cd /opt/sertal
tar -xvzf tablet-reporting-test.tgz
mv bundle tablet-reporting-test
cd /opt/sertal/tablet-reporting-test/programs/server/node_modules
rm -Rf fibers
npm install fibers
this is how the app is started:
MONGO_URL="mongodb://localhost:27017/tablet-reporting-test" PORT=4020 ROOT_URL="http://dev.sertal.ch:4020" node tablet-reporting-test/main.js
it says
LISTENING
You might have the force-ssl package installed.
meteor remove force-ssl
Then rebundle and redeploy. Please let know if it doesn't work it might be some proxy thing instead.

Resources