How do I build docker images when my development environment mounts my codebase into the container?

后端 未结 1 369
青春惊慌失措
青春惊慌失措 2020-12-04 02:35

I dockerized my app, but in order to see my changes, I would have to rebuild my image and it wouldn\'t give me a live preview of my app.

So I created a docker-compos

相关标签:
1条回答
  • 2020-12-04 03:14

    The container image you develop with and mount directories in should be the same image you produce to run the app elsewhere, or at least based the production image if that can't be achieved.

    Using a simple node app as an example, here is the base image:

    FROM node:6
    ENV NODE_ENV=production
    RUN npm install forever -g
    COPY docker-entrypoint.sh /entrypoint.sh
    WORKDIR /app
    COPY package.json /app/
    RUN npm install
    COPY . /app
    EXPOSE 3000
    ENTRYPOINT ["/entrypoint.sh"]
    CMD ["node", "/app/index.js"]
    

    Production

    docker run \
      --detach \
      --restart always \
      --publish 3000:3000 \
      myapp
    

    Development

    docker run \
      --publish 3000:3000 \
      --volume .:/app \
      --env NODE_ENV=development \
      myapp \
      forever -w /app/index.js
    

    So I've modified the mount, but the base image is the same. The mounted files replace the "built" files in the container.

    In the case of a node.js application, there's a couple of extra development changes. An environment variable and the command used to watch/restart the process on changes. You also need to manually exec an npm install in the container with docker exec $container npm install when you make changes to the dependencies in package.json.

    Development Dockerfile

    If you require a number of modifications for a development environment and don't want to specify them manually you can create a development image FROM your base image that houses the development specifics. Dockerfile.dev:

    from myapp:latest
    env NODE_ENV=development
    volume ["/app"]
    command ["forever", "-w", "--watchDirectory", "/app" "/app/index.js"]
    

    Then the dev specifics are stored in the new image but still linked to your real image.

    docker build -f Dockerfile.dev -t myapp-dev .
    docker run -p 3000:3000 -v .:/app myapp-dev
    
    0 讨论(0)
提交回复
热议问题