#Code not running inside Docker

66 messages · Page 1 of 1 (latest)

full pond
#

I'm following a simple tutorial, and for some reason the logs aren't being printed while inside docker (using standalone build).
Am I missing something?

import { prisma } from "@/db";
import Link from "next/link";

export default async function Home() {

  console.log("hello")

  const todos = await prisma.todo.findMany()

  console.log(todos)

  return (<>
    <header className="flex justify-between items-center mb-4">
      <h1 className="text-4xl font-bold">Todos</h1>
      <Link href="new" className="border px-2 py-1 rounded">New</Link>
    </header>

    <ul className="pl-4">
      {todos.map(todo => (
        <li key={todo.id} className="mb-2">
          <Link href={`http://localhost:3000/${todo.id}`} className="border px-2 py-1 rounded">
            {todo.title}
          </Link>
        </li>
      ))}
      
    </ul>
  </>)
}

The UI renders normally, buttons work - but for some reason the JS isn't being ran.

lucid ferryBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

full pond
#

It works as expected in the dev enviroment (next dev)

fading hornet
#

do you have npx prisma generate in dockerfile

full pond
#

here's the docker log

2023-11-16 21:21:52 Environment variables loaded from .env
2023-11-16 21:21:52 Prisma schema loaded from prisma/schema.prisma
2023-11-16 21:21:52 Datasource "db": SQLite database "dev.db" at "file:./dev.db"
2023-11-16 21:21:52 
2023-11-16 21:21:52 1 migration found in prisma/migrations
2023-11-16 21:21:52 
2023-11-16 21:21:52 
2023-11-16 21:21:52 No pending migrations to apply.
2023-11-16 21:21:52    ▲ Next.js 14.0.2
2023-11-16 21:21:52    - Local:        http://d3e5e7d726ea:3000
2023-11-16 21:21:52    - Network:      http://172.17.0.2:3000
2023-11-16 21:21:52 
2023-11-16 21:21:52  ✓ Ready in 43ms
2023-11-16 21:21:48 npm WARN exec The following package was not found and will be installed: [email protected]
2023-11-16 21:21:52 npm notice 
2023-11-16 21:21:52 npm notice New minor version of npm available! 10.1.0 -> 10.2.4
2023-11-16 21:21:52 npm notice Changelog: <https://github.com/npm/cli/releases/tag/v10.2.4>
2023-11-16 21:21:52 npm notice Run `npm install -g [email protected]` to update!
2023-11-16 21:21:52 npm notice
full pond
#
FROM node:20-alpine AS deps

#https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine
RUN apk update && apk add --no-cache libc6-compat && apk add git

WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

# Rebuild the source code only when needed
FROM node:20-alpine AS builder
WORKDIR /app
COPY . .
COPY --from=deps /app/node_modules ./node_modules
ARG NODE_ENV=production
RUN echo ${NODE_ENV}
RUN npx prisma generate
RUN npm run build

FROM node:20-alpine AS runner
WORKDIR /app
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

#copy next config js if not using default config
COPY --from=builder /app/next.config.js ./next.config.js
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json

COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

COPY --chown=nextjs:nodejs prisma ./prisma/
COPY --chown=nextjs:nodejs bootstrap.sh ./

USER nextjs
EXPOSE 3000
ENV PORT 3000
CMD ["./bootstrap.sh"]

dockerfile here

#

Then in boostrap.sh

#!/bin/sh
# Run migrations
DATABASE_URL="file:./dev.db" npx prisma migrate deploy
# start app
DATABASE_URL="file:./dev.db" node server.js
#

nextConfig has output: 'standalone',

fading hornet
#

does the db have data in it?

full pond
#

Not atm. Although, not even console.log("hello") gets logged.

fading hornet
full pond
#

Inside the docker container

#

so on the server side

#

for example, on the dev enviroment I am seeing this

hello
prisma:query SELECT `main`.`Todo`.`id`, `main`.`Todo`.`createdAt`, `main`.`Todo`.`updatedAt`, `main`.`Todo`.`title`, `main`.`Todo`.`content`, `main`.`Todo`.`done` FROM `main`.`Todo` WHERE 1=1 LIMIT ? OFFSET ?
[]
#

in docker, this doesn't get logged for some reason.

#

I've done some digging. If I create a function that runs onclick and console.log in there, it works.

Seems like it doesn't those when I load the page. Are there some exceptions for standalone mode?

#
import { prisma } from "@/db";
import Link from "next/link";
import { redirect } from "next/navigation";

async function createTodo(data: FormData) {
  "use server"

  console.log("TEST")

  const title = data.get("title")
  if(!title) {
    throw new Error("Title is required");
  }

  await prisma.todo.create({data: {title: title.toString(),content: 'Learn how to use Prisma',},})

  redirect("http://localhost:3000/")
}

export default function Home() {

  console.log("HELLO WORLD")

  return (
    <>
      <header className="flex justify-between items-center mb-4">
        <h1 className="text-4xl font-bold">Todos!!</h1>
      </header>
      <form action={createTodo} className="flex gap-2 flex-col">
        <input type="text" name="title" className="border border-slate-300 bg-transparent rounded px-2 py-1 outline-none focus-within:border-slate-100" />
        <div className="flex gap-1 justify-end">
          <Link href=".." className="border px-2 py-1 rounded">Cancel</Link>
          <button type="submit" className="border px-2 py-1 rounded">Create</button>
        </div>
      </form>
    </>
  );
}

so here, only TEST gets logged. HELLO WORLD never gets logged.

fading hornet
#

I don't get console.log in production build too

full pond
#

Hm, I see. Although, if I add an item in the DB I see the query:

prisma:query BEGIN
prisma:query INSERT INTO `main`.`Todo` (`id`, `createdAt`, `updatedAt`, `title`, `content`, `done`) VALUES (?,?,?,?,?,?) RETURNING `id` AS `id`
prisma:query SELECT `main`.`Todo`.`id`, `main`.`Todo`.`createdAt`, `main`.`Todo`.`updatedAt`, `main`.`Todo`.`title`, `main`.`Todo`.`content`, `main`.`Todo`.`done` FROM `main`.`Todo` WHERE `main`.`Todo`.`id` = ? LIMIT ? OFFSET ?       
prisma:query COMMIT

then it redirects it me back, and I don't see anything printed out - nothing on the screen as well.

#

If I extract the db, I can see the item I inserted inside.

full pond
fading hornet
#

do you see the item if you refresh the page

fading hornet
#

try add export const dynamic = 'force-dynamic' in your page

#

and use revalidatePath("/") instead of redirect

full pond
#

revalidatePath didn't seem to work. Redirect worked fine

#

it works as expected though!

#

are there any advantages using revalidatePath here?

fading hornet
#

redirect cause the whole page refresh

full pond
#

not sure why revalidatePath didn't work tho. It just refreshed the page.

#

I am adding on /new, and listing on /

#

probably that's the reason?

fading hornet
#

so now redirect will update the data right?

#

just revalidatePath not updating?

full pond
#

well, will revalidatePath redirect for me?

#

because it's a different page

fading hornet
#

oh use redirect if it is not in the same page

full pond
#

i see

#

Why would I have to use this though?

export const dynamic = 'force-dynamic'

fading hornet
#

because its static page by default

full pond
#

why did it work in the dev mode tho? If you don't mind explaining? 🙂

fading hornet
#

because the static page only being generated when you run next build

full pond
#

See, what seems strange to me is that I am redirecting back. Wouldn't that force the page to "reload"?

#

ahhh

#

Static rendering means that components are pre-rendered on the server at build time ( next build ). The result of this prerendering is cached and then served. Dynamic rendering means that components are rendered on the server at request time. The result of this (pre)rendering is not cached.

#

Well, to my understanding - every page with content that I want to update real-time or with user interaction (like tables, lists etc.) need to be dynamuic?

full pond
#

mhmm I see

#

and because I have
const todos = await prisma.todo.findMany()

#

this is not ran at build time, but at request

#

so build-time would be just hard-coded information, right? theoretically

fading hornet
#

it is run in build time if the page is static

full pond
#

And what'd you mean with this?

yes or use tag to revalidate after update

fading hornet
#

if you use fetch, it can be specific the cache strategy

full pond
#

Sorry for stupid questions, I'm coming from React/Node, so this is really new to me haha

full pond
fading hornet
#

you can leave it dynamic or use cache and revalidate with tag after update

#

since you are using prisma, you cannot use the next fetch

#

that's why you need export const dynamic

#

or use unstable_noStore

full pond
#

Great, got it not! Thanks! 😄