Synchronize Docker volumes

Hey there! I've been trying to dive into learning Docker, but I'm having trouble syncing the host and container using volumes when making changes and saving code (specifically using npm run dev). Every time I need to restart docker-compose up --build for the "sync" to take effect, but even then any changes don't update the folder or code. Here's an example of my setup:

I installed Next.js with typescript as the base.

npx create-next-app@latest --ts

Here's my docker-compose config:

version: "3"
services:
  node-myname:
    build:
      context: .
      dockerfile: DockerFile.dev
    ports:
      - "3000:3000"
    command: "npm run dev"
    restart: always
    volumes:
      - .:/usr/src/home/node/app/
  

And here's my DockerFile:

FROM node:16

WORKDIR /home/node/app

COPY . .

RUN npm install

I know it's recommended to use volumes instead of bind mounts...

But unfortunately, I haven't been able to find a workaround yet. Any suggestions would be greatly appreciated!

Answer №1

After completely reinstalling Docker on Windows (using Revo Uninstaller), the synchronization is now working perfectly. I am able to create a .txt file and see it reflected in the docker exec! However, the hot reload feature using dev was not functioning properly in Docker. The issue was resolved by following a helpful post on StackOverflow: Solution for Docker Hot Reload. This solution required installing something in the next.config.js.

Another observation is that if I copy all the content from the Nextjs host to the Docker container, the sync stops working again. Therefore, I can only copy COPY package.json ./ from the host.

Here is the code snippet from next.config.js:

 /** @type {import('next').NextConfig} */
    const nextConfig = {
      reactStrictMode: true,
      swcMinify: true,
      // add this for hot reload to work on Windows
      webpackDevMiddleware: config => {
        config.watchOptions = {
          poll: 800,
          aggregateTimeout: 300,
        }
        return config
      },
    }
    
    module.exports = nextConfig

And here is the Dockerfile:

FROM node:16

WORKDIR /home/node/app

COPY package.json ./

RUN npm install

Finally, here is the docker-compose configuration:

version: "3"
services:
  node-myname:
    build:
      context: .
      dockerfile: DockerFile.dev
    ports:
      - "3000:3000"
    command: "npm run dev"
    restart: always
    volumes:
      - .:/home/node/app
  

With these changes, everything now works as intended. Although I'm not sure why, attempting the same approach as before resulted in an error. Nevertheless, everything is functioning correctly now!

Final Code on GitHub

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my controller method in TypeScript to throw an error message unexpectedly?

Hey there. I'm diving into TypeScript and currently working on converting an Express backend to TS. Everything was smooth sailing until I encountered some unexpected issues. Specifically, the lines const hasVoted = poll.votedBy.some((voter): boolean = ...

What is the most effective method for comparing two arrays of objects and extracting the differing values within a React application?

I am currently working on implementing a changelog feature for my website. Let's consider the initial array as initArray: [ { "id": 1, "val1": "2023-08-28", "val2": 1, " ...

Oops! The system encountered a problem: the property 'modalStack' is not recognized on the type 'NgxSmartModalService'. Maybe you meant to use '_modalStack' instead?

Currently, I'm facing an issue while attempting to run ng build --prod in my Angular 6 project. I have also incorporated the NgxSmartModal package for handling modals. Unfortunately, the build process is failing and I can't seem to figure out why ...

Issue: The useHref() function is restricted to usage within a <Router> component. This error occurred within the register.js file

Hey there, I'm currently working on a reactjs app and everything is running smoothly with the routes except for the register user function which is throwing an error: Error: useHref() may be used only in the context of a component. I am utilizing fire ...

Having trouble with implementing custom checkboxes in a d3 legend?

My attempt at creating checkboxes in d3 has hit a snag. Upon mouse click, the intention is for them to be filled with an "x". Strangely, using d3.select() inside the click-function doesn't seem to work as expected, although adding the letter U for the ...

The counterpart of the RxJS setTimeout operator

Looking for a RxJS operator alternative to set/clearTimeout in these circumstances: this.mouseEnterSubscription = this.mouseEnterStream .subscribe(() => { this.timeout = setTimeout(() => { void this.playVideo(); }, 500) }); this.mo ...

Error: Unable to find the definition for Image (Next.js)

This new component in my next js project allows me to write a quote on an image and display it on the canvas. However, I am encountering an issue with the Image() function in JavaScript which typically runs on the browser. It seems that Next.js first execu ...

Dealing with circular dependencies in NestJS by using ForwardRef

Hey everyone, I've been running into a circular dependency issue with NestJS. I tried using the forwardref method, but it hasn't resolved the problem for me. // AuthModule @Module({ imports: [ forwardRef(() => UserModule), JwtModule ...

The issue arises when attempting to call a method from the same service within jsPDF in an Angular environment

Below you will find my Angular project's pdfService. I am facing an issue where calling the this.formatter() method inside myPDF is not functioning properly. export class pdfService { formatter(value: number): string { return new Intl.N ...

Are you looking to use the 'any' type instead of the 'Object' type? Angular Services can help you with that

I encountered the following error message: Argument of type 'OperatorFunction<APISearch[], APISearch[]>' is not assignable to >parameter of type 'OperatorFunction<Object, APISearch[]>'. The 'Object' type is ...

Creating type definitions for recursive functions in TypeScript

I've created a JavaScript function that continuously accepts functions(params => string) until it receives an object, at which point it resolves the final string as a concatenation of all the functions invoked over the same object passed in at the ...

Importing multiple modules in Typescript is a common practice

I need to include the 'express' module in my app. According to Mozilla's documentation, we should use the following code: import { Application }, * as Express from 'express' However, when using it in TypeScript and VSCode, I enc ...

The type does not meet the requirements set by the class it is inheriting from

Currently, I am in the process of working on a WebSocket Secure (WSS) server utilizing the Node ws library which can be found here. More specifically, I am following the approach outlined in this particular question, although its relevance is yet to be det ...

Steps for connecting to a property in another component

As a newcomer to Angular, I am exploring new concepts for the first time. I have a custom component called Timeselector with an Apply button whose enable/disable state is determined by validations performed in another custom component called Monthpicker. C ...

Failure to connect to the NextJS API resulting in rejection of Incremental Static Regeneration requests

My NodeJS server is set up to send a post request every time a user adds a product for incremental static regeneration. Next, I have my NextJS application running on port 3000 and NodeJS on port 3001. Below is the code snippet from my /api/revalidate file ...

1. "The power of three vows in the world

I encountered an issue while making three HTTP Post requests in my code. The first two requests are successful, and upon debugging the code, they return the correct values. However, the third request returns undefined. The reason behind making these three ...

An unparalleled nextjs middleware that seamlessly functions across all routes without requiring individual imports

TLDR; A middleware similar to express for Next.js where I can define it once and have it automatically apply to all routes. I am looking for a middleware style like what we have in express. Ideally, I would define the middleware in the server.js (entry f ...

Unable to utilize vue-cookies library in TypeScript environment

I have integrated vue-cookies into my app in the main.ts file: import VueCookies from 'vue-cookies'; ... const app = createApp(App) .use(IonicVue) .use(router) .use(VueCookies,{ expires: '30d', }); Despite adding the cookie v ...

When elements are passed through components in Next.js, their style does not get applied

I have a unique component for the hero section of every page with varying content and heights. export default function CustomHero({ height, children, }: { height: string; children: ReactNode; }) { return ( <div className={`flex flex- ...

Mobile values in tailwindcss take precedence over breakpoints values, overriding them

I have encountered a puzzling issue that seems to have no answers thus far. Whenever I set paddings or margins for mobile devices and attempt to adjust these values for larger screens, the original mobile base value stubbornly persists and overrides my sp ...