{"id":19540566,"url":"https://github.com/yuhexiong/pyinstaller-build-binary-docker-image-guide","last_synced_at":"2026-04-29T02:41:33.768Z","repository":{"id":261523531,"uuid":"883596886","full_name":"yuhexiong/pyinstaller-build-binary-docker-image-guide","owner":"yuhexiong","description":null,"archived":false,"fork":false,"pushed_at":"2024-11-18T01:23:54.000Z","size":17,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-26T05:16:31.952Z","etag":null,"topics":["docker","docker-image","pyinstaller"],"latest_commit_sha":null,"homepage":"","language":"Dockerfile","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yuhexiong.png","metadata":{"files":{"readme":"README-CH.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-05T08:47:56.000Z","updated_at":"2024-11-18T01:23:58.000Z","dependencies_parsed_at":"2024-11-07T02:28:04.259Z","dependency_job_id":"663844a1-0943-484e-8d2b-d544e42dabe8","html_url":"https://github.com/yuhexiong/pyinstaller-build-binary-docker-image-guide","commit_stats":null,"previous_names":["yuhexiong/pyinstaller-build-binary-docker-image-guide"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/yuhexiong/pyinstaller-build-binary-docker-image-guide","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yuhexiong%2Fpyinstaller-build-binary-docker-image-guide","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yuhexiong%2Fpyinstaller-build-binary-docker-image-guide/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yuhexiong%2Fpyinstaller-build-binary-docker-image-guide/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yuhexiong%2Fpyinstaller-build-binary-docker-image-guide/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yuhexiong","download_url":"https://codeload.github.com/yuhexiong/pyinstaller-build-binary-docker-image-guide/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yuhexiong%2Fpyinstaller-build-binary-docker-image-guide/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263550840,"owners_count":23478874,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["docker","docker-image","pyinstaller"],"created_at":"2024-11-11T03:04:54.401Z","updated_at":"2026-04-29T02:41:28.719Z","avatar_url":"https://github.com/yuhexiong.png","language":"Dockerfile","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PyInstaller Build Binary Docker Image Guide\n\n使用 PyInstaller 將專案打包成 binary 檔來建立 Docker Image，包括所有所需的套件，並使用 Docker Compose 啟動它，同時掛載設定檔。\n\n\n## Overview\n\n- Language: Python v3.12\n- Tool: PyInstaller v6.11.0\n\n## PyInstaller Introduction\n\n參考 [PyInstaller 官方手冊](https://pyinstaller.org/en/stable/)  \nPyInstaller 可以將 Python 專案打包成可執行檔，方便在沒有 Python 環境的機器上直接執行。  \n\n### Basic Command\n\n#### 將 `{ENTRY_FILE}.py` 打包成可執行檔的基本指令\n```sh\npyinstaller {ENTRY_FILE}.py\n```\n\n#### 設定打包後的檔案名稱為 `{EXECUTABLE_FILE_NAME}`\n```sh\npyinstaller -n {EXECUTABLE_FILE_NAME} {ENTRY_FILE}.py\n```\n\n### Issues and Solutions\n\n- **打包後產生多個檔案**  \n   預設情況下，PyInstaller 會在當前目錄下生成 `build` 資料夾，內含多個檔案。如果希望只生成一個可執行檔，可使用 `--onefile` 參數。執行後可執行檔會放在 `dist` 資料夾中：\n\n- **跨平台相容性**  \n   在 Windows 環境下生成的檔案為 `.exe` 格式，無法在 Linux 環境中執行。為避免相容性問題，直接在 Dockerfile 中打包，以確保執行環境一致。\n\n- **套件依賴處理**  \n   PyInstaller 需要將所有依賴的套件一同打包。可以撰寫 `requirements.txt`，安裝後使用 `--collect-all` 參數以確保所有套件都被包含：\n\n- **檔案路徑問題**  \n   打包後的程式在運行時，會暫時解壓至 `/tmp` 資料夾，而外部掛載的設定檔掛載於`/app`，因此必須根據執行環境（`/tmp` 或 `/app`）調整路徑`BASE_DIR` 變數來設定正確的目錄位置。\n\n### Custom Command\n\n結合上面，我們使用的指令如下，會於之後的步驟中放入 Dockerfile  \n```bash\npyinstaller --onefile -n {EXECUTABLE_FILE_NAME} --collect-all {MODULE} {ENTRY_FILE}.py\n```\n\n## Steps\n\n實作步驟分為 4 步。\n\n### 1. Adjust Code\n\n參考 [Stackoverflow 問題](https://stackoverflow.com/questions/70405069/pyinstaller-executable-saves-files-to-temp-folder)  \n\n原先我們使用\n\n```py\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n```\n\n但在使用 PyInstaller 建置後，實際上是在 /tmp 下面的某個資料夾中運行檔案。  \n因此，我們需要區分一起打包進去的程式路徑和掛載的設定檔路徑。\n\n```py\n# get the base directory for the main script\ndef get_base_dir():\n    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):\n        base_dir = os.path.dirname(sys.executable)\n    else:\n        base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n    return base_dir\nBASE_DIR = get_base_dir()\n\n# get the temporary directory used by PyInstaller\ndef get_data_folder():\n    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):\n        data_folder_path = sys._MEIPASS\n    else:\n        data_folder_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n    return data_folder_path\nDATA_DIR = get_data_folder()\n```\n\n除此之外還要修改程式碼中的資料夾路徑，YAML 路徑使用 `BASE_DIR`，而程式路徑使用 `DATA_DIR`。\n\n\n### 2. Write Down Required Modules\n\n將所需的套件寫入 `requirements.txt`  \n\n如果你使用 .venv，可以選擇以指令將 module 導出成 `requirements.txt`，或不處理但在下一個步驟時直接使用 `DockerfilePoetry`  \n```bash\npip freeze \u003e requirements.txt\n```\n\n### 3. Dockerfile\n\n**(1) 使用 `requirements.txt`**  \n\n參考 [Dockerfile](Dockerfile)  \n\n**(2) 使用 `poetry`**  \n\n參考 [DockerfilePoetry](DockerfilePoetry)  \n\n在 Dockerfile 中，你需要將 `{EXECUTABLE_FILE_NAME}` 修改為所需的檔名，將 `{MODULE}` 修改為需要包含的套件，將 `{ENTRY_FILE}` 修改為專案的入口檔案，通常是 manage.py 或 main.py，並修改運行 Python的指令。  \n\n詳細實作步驟：  \n- 安裝所需的依賴和函式庫（請根據需要進行調整）。\n- 將程式碼複製到 image 內。\n- 根據 `requirements.txt` 安裝套件或 poetry install。\n- 安裝 PyInstaller，將其建置成一個檔案，該檔案將自動生成在 /dist 資料夾下。\n- 使用新的 image，只複製 /dist 資料夾中的執行檔，以減少 image 大小。\n\n### 4. Docker Compose\n\n參考 [docker-compose.yml](docker-compose.yml)  \n將設定檔掛載到 `/app` 下  \n\n```bash\ndocker-compose up -d\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyuhexiong%2Fpyinstaller-build-binary-docker-image-guide","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyuhexiong%2Fpyinstaller-build-binary-docker-image-guide","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyuhexiong%2Fpyinstaller-build-binary-docker-image-guide/lists"}