---
title: "在 Docker 容器中获取和显示 Git 部署版本号的折腾记录"
url: "https://versun.me/getting-and-displaying-git-deployment-hash-in-docker-containers"
markdown_url: "https://versun.me/getting-and-displaying-git-deployment-hash-in-docker-containers.md"
format: "note"
published: "2025-02-11T08:17:11.000Z"
updated: "2026-01-05T05:31:57.000Z"
collections:
  - "Blog"
site: "Versun"
---

# 在 Docker 容器中获取和显示 Git 部署版本号的折腾记录

昨天晚上，我准备给我的 CMS 添加显示 deploy git hash 的功能，方便跟踪当前博客部署所使用的最新提交 hash，以判断是否需要更新，或者更新是否成功。  
最开始，我直接执行 git 命令获取 HEAD 所在的 hash 值[(commit)](https://github.com/versun/VersunCMS/commit/bf8de92bd18eff637df8dc34d6d28af38e60fa14#diff-c1fd91cb1911a0512578b99f657554526f3e1421decdb9e908712beab57e10f9)：

```
    def self.git_version
      @git_version ||= `git rev-parse HEAD`.strip[0..7]
    end
```

但失败了，非常低级的错误：系统没有找到 git 命令。。。。

随后，我在 Dockerfile 中添加了 git 包，以便系统安装 git ([commit](https://github.com/versun/VersunCMS/commit/f63d2c5f9c27fea9dea19afb1d827683b2501c87))

![tweet-2083406124397822426-fed78e42.jpg](https://media.jant.me/media/sit_01krgk4fnyf24sfk8an30re4xv/files/med_01m94p5bcpea3vg3btz0mx7mmp.jpg)  
但又失败了：

```
fatal: not a git repository (or any of the parent directories): .git
```

我忘记 Dockerfile 中的 COPY 命令默认是不会复制 .git 目录的。

所以最后决定直接在 Dockerfile 中执行命令并输出 hash 到 REVISION 文件中，然后 Rails 直接读取该文件即可。  
[Dockerfile](https://github.com/versun/VersunCMS/blob/main/Dockerfile) 添加了下面的代码：

```
COPY .git /rails/.git
RUN git rev-parse HEAD > REVISION  && \
    rm -rf .git
RUN chown -R rails:rails REVISION
```

重新 [git\_version](https://github.com/versun/VersunCMS/blob/main/config/application.rb#L19) 函数：

```
  def self.git_version
      @git_version ||= begin
        if File.exist?("REVISION")
          File.read("REVISION").strip[0..7]
        else
          "NA"
        end
      end
    end
```

最后在相关的 [html.erb](https://github.com/versun/VersunCMS/blob/main/app/views/settings/edit.html.erb) 文件中添加：

```
<span>Depoly Git Hash: <%= VersunCms::Application.git_version %></span>
```

效果如下  
![tweet-2083719150833463349-6b376348.jpg](https://media.jant.me/media/sit_01krgk4fnyf24sfk8an30re4xv/files/med_01m94p5dd4ehkaxhc734wbafef.jpg)
