This way you can develop your stuff in Docker through a mounted volume, and still see the changes in real-time.
Many thanks to Pas.
docker-compose.yml
# docker-compose.yml
services:
db:
# ...
web:
# ...
next:
build: nextjs-blog
image: blog-next:latest
container_name: blog-next
depends_on:
- db
volumes:
- ./nextjs-blog:/app
ports:
- "8101:3000"
stdin_open: true
tty: true
proxy:
# ...
Dockerfile
# nextjs-blog/Dockerfile:
FROM node:22
WORKDIR /app
CMD node npm-install.mjs && npm run dev
npm-install.mjs
# nextjs-blog/npm-install.mjs:
import {existsSync, readFileSync, writeFileSync} from 'fs';
import {spawn} from 'child_process'
import {createHash} from 'crypto'
const run = async () => {
const child = spawn('sh', ['-c', 'npm install']);
child.stdout.setEncoding('utf8');
child.stdout.on('data', function(data) {
console.log(data);
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', function(data) {
console.log(data);
});
const p = new Promise((resolve, reject) => {
child.on('exit', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`npm install failed with code ${code}`));
}
});
});
await p;
return child;
}
const sha1 = (input) => createHash('sha1').update(input).digest('hex')
const getHash = () => {
const packageJson = readFileSync('package.json', 'utf8');
const packageLockJson = readFileSync('package-lock.json', 'utf8');
return sha1(packageJson + packageLockJson);
};
const directoryExists = (path) => existsSync(path);
const fileExists = (path) => existsSync(path);
const readFile = (path) => readFileSync(path, 'utf8');
console.log("Hello, 33");
const main = async () => {
if (directoryExists('node_modules')) {
if (fileExists('node_modules/hash.txt') && fileExists('package-lock.json')) {
console.log("Checking for hash, 37");
const expectedHash = readFile('node_modules/hash.txt');
const hash = getHash();
if (hash === expectedHash) {
console.log('No npm install needed');
process.exit(0);
}
}
console.log('npm install needed, 47');
// npm install needed
const npmInstall = await run();
if (npmInstall.error) {
console.error('Error occurred during npm install:', npmInstall.error);
process.exit(1);
}
writeFileSync('node_modules/hash.txt', getHash());
} else {
console.error('Directory "node_modules" does not exist. Please run "npm install" first.');
process.exit(1);
}
}
main();
Now watching Next.js 14 Full Course 2024