【问题标题】:Using git inside docker containers在 docker 容器中使用 git
【发布时间】:2020-09-18 09:50:44
【问题描述】:

我正在使用 Docker-compose 将我的 webapp 拆分为两个容器。 项目文件夹层次结构如下所示:

  • 应用/
    • .git/
    • 前端/
      • Dockerfile
    • 后端/
      • Dockerfile
    • docker-compose.yml

我使用 VSCode 上的 Remote-Containers 扩展直接在我的容器中工作,这样我就不必为每次更改都重新构建我的容器。我也想在我的容器中使用 git。但我不确定如何将 .git/ 文件夹复制到我的容器中,因为它在 Dockerfile 的上下文之外。

我的 docker-compose.yml:

services:
    angular: # name of the first container
        build: ./frontend
        ports:
            - "8080:8080"
    
    express: # name of the second container
        build: ./backend
        ports:
            - "8081:8081"

我的前端/Dockerfile:

FROM node:10.18.0-alpine AS build
WORKDIR /usr/src/app

COPY ./../.git .   # doesn't work!

# copy package.json & install dependencies
COPY package.json .
RUN npm cache clean --force
RUN npm install

# copy files to /usr/src/app
COPY . .

EXPOSE 8080

# call start script from package.json
CMD ["npm","start"]

【问题讨论】:

    标签: git docker


    【解决方案1】:

    我不确定复制.git 目录是否是个好主意。但是,如果您确定有必要,可以通过以下方式获得它。

    docker build [OPTIONS] PATH 命令从 Dockerfile 和“上下文”构建 Docker 映像。构建的上下文是位于指定 PATH 中的文件集。

    因此,在 Dockerfile 中,您不能引用不在构建上下文中的目录。

    COPY ./../.git .   # parent directory of the build context doesn't work!
    

    相反,您可以从父目录构建 Dockerfile。 编辑frontend/Dockerfile

    #...
    WORKDIR /usr/src/app 
    COPY .git . 
    COPY frontend . 
    WORKDIR /usr/src/app/frontend 
    #...
    RUN npm install
    #...
    

    并使用以下命令

    docker build -t angular-frontend -f frontend/Dockerfile .
    

    docker-compose.yaml

    services:
      angular:
        build:
          context: .
          dockerfile: frontend/Dockerfile
        ports:
          - "8080:8080"
    

    【讨论】:

    • 谢谢,我可以从容器中看到我的 git 日志。我面临另一个问题:从字面上看,我容器中的每个项目文件都被标记为已修改。你知道为什么会发生这种情况吗?或者这是一个与 Docker 无关的不同问题?
    • 你必须保留目录结构:WORKDIR /usr/src/appCOPY .git .COPY frontend .WORKDIR /usr/src/app/frontendRUN npm install
    猜你喜欢
    • 2019-02-13
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多