Reputation: 611
I am encountering an issue with loading environment variable in my SvelteKit application when running it inside a Docker container. This question is extended from this question
The error I'm seeing is:
SvelteKitError: Not found: /undefined/get-paginated
at resolve2 (file:///app/build/server/index.js:3850:18)
at resolve (file:///app/build/server/index.js:3682:34)
at Object.handle (file:///app/build/server/chunks/hooks.server-JRK4nkXw.js:31:26)
at respond (file:///app/build/server/index.js:3680:43)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
status: 404,
text: 'Not Found'
}
Dockerfile:
FROM node AS builder
WORKDIR /app
COPY package*.json .
RUN npm ci
COPY . .
RUN npm run build
RUN npm prune --production
FROM node
WORKDIR /app
COPY --from=builder /app/build build/
COPY --from=builder /app/node_modules node_modules/
COPY package.json .
EXPOSE 3000
ENV NODE_ENV=production
CMD ["node", "build"]
Docker run command:
docker build -t my-frontend . //build successfully.
docker run -p 3000:3000 \
-e PUBLIC_BACKEND_SERVER_URL=http://localhost:4000 \
my-frontend
When I build and run the application without Docker, it works as expected. The build process is following the SvelteKit documentation on environment variables.
import { get, type Writable } from "svelte/store";
import { collectionObj } from "./store";
import { PUBLIC_BACKEND_SERVER_URL } from "$env/static/public";
// Define the options for the fetch request
const options = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({...}),
};
// Fetch function to get paginated posts
export const fetchPaginatedPosts = async (key: string = "posts", last_id: string = "") => {
collectionObj.set(key);
console.log("de: ", get(collectionObj));
try {
const response = await fetch(
`${PUBLIC_BACKEND_SERVER_URL}/get-paginated`,
options
);
if (!response.ok) {
throw new Error("Network response was not ok");
}
const res = await response.json();
console.log("API call");
return res;
} catch (error) {
console.error(error);
throw error;
}
};
svelte.config.js:
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter({ out: 'build', precompress: false, envPrefix: '', polyfill: true })
}
};
export default config;
What could be causing the /undefined/get-paginated
error in the Docker container, and how can I resolve it?
Upvotes: 0
Views: 360
Reputation: 611
Add this line before RUN npm run build
ENV YOUR_ENV_VARIABLE=http://localhost:4000
OR,
remove following line from .dockerignore
:
**/.env
then add this line before RUN npm run build
COPY .env .env
Upvotes: 0