I had the same problem that the NEXT_PUBLIC environment variables on my Azure AppService always had the value "undefined", although they were defined as environment variables in the AppService settings.
When building the Docker image, the NEXT_PUBLIC environment variables are set directly during the build and cannot be overwritten afterwards. This was the reason why the settings from the AppService for the NEXT_PUBLIC did not work.
The following solution by Renato Pozzi (dev.to) helped me.
Here are my steps: (next v.12.2.5):
a) Create the desired NEXT_PUBLIC variable in the Dockerfile before the "build" process start and fill it with a "placeholder value".
RUN NEXT_PUBLIC_API_URL=PLACEHOLDER_NEXT_PUBLIC_API_URL yarn build
b) Create an entrypoint file (entrypoint.sh) which replaces the placeholder value with real environment variables from the AppService when the Docker image start.
In my example, the placeholder "PLACEHOLDER_NEXT_PUBLIC_API_URL" is replaced with the real value "NEXT_PUBLIC_API_URL" from the AppService configurations (environment variables).
#!/bin/sh
test -n "$NEXT_PUBLIC_API_URL"
find /app/.next \( -type d -name .git -prune \) -o -type f -print0 | xargs -0 sed -i "s#PLACEHOLDER_NEXT_PUBLIC_API_URL#$NEXT_PUBLIC_API_URL#g"
exec "$@"
c) Make the previously created entry point file known in the Dockerfile.
COPY --chown=nextjs:nodejs entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD ["node", "server.js"]