Codex CLI 云环境部署实操指南

编写日期:2026-04-29 | 基于 Codex CLI 2026 Q1 版本(Rust 核心,npm 分发)


一、Codex CLI 概述

OpenAI Codex CLI 是一个开源(Apache-2.0)Rust 实现的终端编码 agent。核心特点:


二、部署场景

场景 A:AWS Lightsail

适合低成本、固定预算的小型团队或个人 CI/CD runner。

系统要求

项目 最低 推荐
实例类型 $5/月 (1 vCPU, 512 MB) $10/月 (1 vCPU, 2 GB)
OS Ubuntu 22.04 LTS Ubuntu 24.04 LTS
Node.js 18+ 22 LTS
磁盘 20 GB SSD 40 GB SSD
网络 出站 HTTPS 到 api.openai.com

⚠️ 512 MB 实例不推荐:npm install 大包时可能 OOM。建议至少 2 GB。

安装步骤

# 1. 更新系统
sudo apt update && sudo apt upgrade -y

# 2. 安装 Node.js 22(LTS)
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt-get install -y nodejs git build-essential

# 验证
node --version  # v22.x
npm --version   # 10.x+

# 3. 安装 Codex CLI
npm install -g @openai/codex

# 4. 配置 API Key(无头模式必须)
export OPENAI_API_KEY="sk-..."
echo 'export OPENAI_API_KEY="sk-..."' >> ~/.bashrc

# 或写入 config.toml
mkdir -p ~/.codex
cat > ~/.codex/config.toml << 'EOF'
preferred_auth_method = "apikey"
model = "gpt-5.3-codex"
approval_policy = "never"
sandbox_mode = "workspace-write"
EOF

# 5. 验证
codex --version
codex exec "echo hello world"

Sandbox 配置

Linux 上 Codex 使用 bubblewrap + Landlock 进行系统级沙箱隔离:

# ~/.codex/config.toml
sandbox_mode = "workspace-write"     # 仅项目目录可写
# 或
sandbox_mode = "read-only"           # 只读模式(code review)
# 或
sandbox_mode = "danger-full-access"  # 无限制(仅可信环境)

对于 Lightsail 上的 CI/CD: - code reviewread-only(最安全) - auto-fixworkspace-write(推荐) - e2e test/部署danger-full-access(需额外安全措施)

Lightsail 特定注意事项

  1. 静态 IP:建议附加静态 IP(免费,避免重启换 IP)
  2. 防火墙:出站需要开放 443 到 api.openai.com;入站仅需 SSH(22)
  3. 自动启动:用 systemd 或 cron 管理定时任务
  4. 磁盘清理~/.codex/sessions/ 会累积 rollout 文件,定期清理
# 清理 30 天前的 session 文件
find ~/.codex/sessions/ -type f -mtime +30 -delete

场景 B:AWS EC2

适合需要更高性能、弹性伸缩或与 AWS 生态集成的场景。

系统要求

项目 最低 推荐
实例类型 t3.micro (2 vCPU, 1 GB) t3.medium (2 vCPU, 4 GB)
AMI Ubuntu 22.04/24.04 或 Amazon Linux 2023 Ubuntu 24.04 LTS
Node.js 18+ 22 LTS
磁盘 20 GB gp3 50 GB gp3
IAM Role 如需 S3 存取则配置

安装步骤

# === Ubuntu 22.04/24.04 ===
sudo apt update && sudo apt upgrade -y

# 安装 Node.js
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt-get install -y nodejs git

# 安装 Codex
npm install -g @openai/codex

# 配置
mkdir -p ~/.codex
cat > ~/.codex/config.toml << 'EOF'
preferred_auth_method = "apikey"
model = "gpt-5.3-codex"
model_reasoning_effort = "high"
approval_policy = "never"
sandbox_mode = "workspace-write"
EOF

export OPENAI_API_KEY="sk-..."
echo 'export OPENAI_API_KEY="sk-..."' >> ~/.bashrc
# === Amazon Linux 2023 ===
sudo dnf update -y
sudo dnf install -y nodejs git

# Node.js 版本可能偏旧,用 nvm 安装新版本
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 22
nvm use 22

npm install -g @openai/codex
# 其余配置同上

Sandbox 配置

# ~/.codex/config.toml — EC2 专用配置
preferred_auth_method = "apikey"
model = "gpt-5.3-codex"
model_reasoning_effort = "medium"
approval_policy = "never"
sandbox_mode = "workspace-write"

# 命名 profile,方便不同任务切换
[profiles.review]
approval_policy = "never"
sandbox_mode = "read-only"
model = "gpt-5-codex-mini"

[profiles.fix]
approval_policy = "never"
sandbox_mode = "workspace-write"
model = "gpt-5.3-codex"
model_reasoning_effort = "high"

EC2 systemd 服务(定时/触发式)

# /etc/systemd/system/codex-agent.service
[Unit]
Description=Codex CLI Agent Runner
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
User=ec2-user
WorkingDirectory=/home/ec2-user/project
Environment="OPENAI_API_KEY=sk-..."
ExecStart=/home/ec2-user/.nvm/versions/node/v22.0.0/bin/codex exec \
  --profile fix \
  "Fix failing tests and create a PR with the changes"

[Install]
WantedBy=multi-user.target
# 定时运行
cat > /etc/systemd/system/codex-agent.timer << 'EOF'
[Unit]
Description=Run Codex agent every 30 minutes

[Timer]
OnCalendar=*:0/30
Persistent=true

[Install]
WantedBy=timers.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable --now codex-agent.timer

Codex + Bedrock 集成(EC2 专属优势)

在 EC2 上可直接接入 Amazon Bedrock,避免 OpenAI API 依赖:

# ~/.codex/config.toml
[model_providers.bedrock]
name = "AmazonBedrock"
base_url = "https://bedrock-mantle.us-west-1.api.aws/v1"
env_key = "CODEX_OPENAI_API_KEY"

[profiles.bedrock]
model = "openai.gpt-oss-120b"
model_provider = "bedrock"
wire_api = "responses"  # Codex 默认使用 /v1/responses API

⚠️ 注意:需要先在 AWS Console 中申请 Bedrock 模型访问权限。


场景 C:GitHub Actions

Codex 提供官方 Action openai/codex-action@v1,是最简洁的 CI/CD 集成方式。

系统要求

安装步骤(最小可用)

# .github/workflows/codex-review.yml
name: Codex PR Review

on:
  pull_request:
    types: [opened, synchronize]

permissions:
  contents: read
  pull-requests: write

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: Codex review
        id: codex
        uses: openai/codex-action@v1
        with:
          openai-api-key: ${{ secrets.OPENAI_API_KEY }}
          prompt: |
            Review this pull request diff for:
            1. Security vulnerabilities
            2. Logic errors
            3. Performance issues
            4. Adherence to project conventions
            Output a concise markdown report.
          sandbox: read-only
          safety-strategy: drop-sudo
          effort: medium
          output-file: review.md

      - name: Post review
        uses: peter-evans/create-or-update-comment@v4
        with:
          issue-number: ${{ github.event.pull_request.number }}
          body-file: review.md

Sandbox 配置

GitHub Actions 中的 sandbox 和 safety-strategy 是两层独立的防护:

sandbox 文件访问 网络 适用
read-only 只读 阻止 Code review、分析
workspace-write 项目根可读写 阻止 Auto-fix、生成文档
danger-full-access 无限制 无限制 集成测试、部署
safety-strategy 效果
drop-sudo(默认) 移除 sudo 权限,当前 job 内不可逆
unprivileged-user 以非 root 用户运行(需自托管 runner)
unsafe 无降权(仅 Windows,避免在共享 runner 使用)

GitHub Actions 工作流模式

模式 1:PR Code Review 门禁

name: Codex Quality Gate

on:
  pull_request:

jobs:
  gate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5

      - name: Quality scan
        id: scan
        uses: openai/codex-action@v1
        with:
          openai-api-key: ${{ secrets.OPENAI_API_KEY }}
          prompt: |
            Analyse the diff. Output ONLY "PASS" if the code meets quality
            standards, or "FAIL: <reason>" if it does not.
          sandbox: read-only
          effort: minimal  # 低延迟 + 低成本

      - name: Enforce gate
        run: |
          RESULT="${{ steps.scan.outputs.final-message }}"
          if [[ "$RESULT" != PASS* ]]; then
            echo "::error::Quality gate failed: $RESULT"
            exit 1
          fi

模式 2:Auto-Fix 失败 CI

name: Codex Auto-Fix

on:
  workflow_run:
    workflows: ["CI"]
    types: [completed]

permissions:
  contents: write
  pull-requests: write

jobs:
  fix:
    if: ${{ github.event.workflow_run.conclusion == 'failure' }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
        with:
          ref: ${{ github.event.workflow_run.head_branch }}

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - run: npm ci

      - name: Codex fix
        uses: openai/codex-action@v1
        with:
          openai-api-key: ${{ secrets.OPENAI_API_KEY }}
          prompt: |
            The CI workflow failed. Identify the minimal change needed
            to make all tests pass. Implement only that change.
          sandbox: workspace-write
          safety-strategy: drop-sudo
          effort: high

      - run: npm test

      - name: Open fix PR
        uses: peter-evans/create-pull-request@v6
        with:
          branch: codex/auto-fix-${{ github.run_id }}
          title: "fix: Codex auto-repair for CI failure"
          body: "Automated fix. Review before merging."

模式 3:矩阵并行(多服务)

name: Parallel Service Review

on:
  push:
    branches: [main]

jobs:
  review:
    strategy:
      matrix:
        service: [auth, payments, notifications, search]
      fail-fast: false  # 一个失败不影响其他
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5

      - name: Review ${{ matrix.service }}
        uses: openai/codex-action@v1
        with:
          openai-api-key: ${{ secrets.OPENAI_API_KEY }}
          prompt: |
            Review the code in services/${{ matrix.service }}/.
            Focus on security, error handling, and test coverage.
            Output a structured JSON report.
          codex-args: >-
            ["--output-schema-file", ".github/codex/schemas/review.json"]
          sandbox: read-only
          effort: medium
          output-file: review-${{ matrix.service }}.json

      - uses: actions/upload-artifact@v4
        with:
          name: review-${{ matrix.service }}
          path: review-${{ matrix.service }}.json

模式 4:结构化 JSON 输出门禁

// .github/codex/schemas/review.json
{
  "type": "object",
  "required": ["severity", "issues", "recommendation"],
  "properties": {
    "severity": {
      "type": "string",
      "enum": ["low", "medium", "high", "critical"]
    },
    "issues": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "file": { "type": "string" },
          "line": { "type": "integer" },
          "description": { "type": "string" }
        }
      }
    },
    "recommendation": { "type": "string" }
  }
}
- name: Security Scan
  id: scan
  uses: openai/codex-action@v1
  with:
    openai-api-key: ${{ secrets.OPENAI_API_KEY }}
    prompt-file: .github/codex/prompts/security-scan.md
    codex-args: '["--output-schema-file", ".github/codex/schemas/review.json"]'
    sandbox: read-only

- name: Fail on critical
  run: |
    SEVERITY=$(echo '${{ steps.scan.outputs.final-message }}' | jq -r '.severity')
    if [ "$SEVERITY" = "critical" ]; then
      echo "::error::Critical security issue found"
      exit 1
    fi

三、无头模式使用指南

codex exec 命令详解

# 基本用法
codex exec "Update the changelog for next release"

# 短别名
codex e "Fix all failing tests"

# 关键参数
codex exec \
  --model gpt-5.3-codex \          # 指定模型
  --sandbox workspace-write \       # 沙箱模式
  --approval-policy never \         # 无需确认(CI 必须)
  --json \                          # JSON 行输出(CI 友好)
  --output-last-message result.md \ # 最终消息写入文件
  --ephemeral \                     # 不持久化 session
  --skip-git-repo-check \           # 允许非 git 仓库
  --profile ci \                    # 加载命名配置
  "Your prompt here"

审批策略

策略 行为 适用场景
untrusted 所有操作都需要确认 高安全环境、首次使用
on-request(默认) Codex 判断是否需要确认 日常开发
never 不询问,直接执行 CI/CD、受控沙箱
reject 拒绝所有需要审批的操作 纯分析场景
# CI/CD 中必须设置 never + workspace-write
codex exec --approval-policy never --sandbox workspace-write "..."

# 或使用 --full-auto 快捷方式(= on-request + workspace-write)
codex --full-auto "refactor auth module"

无头模式与交互模式的差异

特性 codex exec codex(交互)
TUI
多轮对话 ❌(单次执行)
Session 持久化 可选 --ephemeral ✅ 自动
JSON 输出 --json
审批中断 ❌(必须预设策略) ✅ 运行时切换
适合 CI/CD

从 exec 恢复 session

# 恢复最近 session
codex exec resume --last

# 恢复指定 session
codex exec resume thr_abc123

# 带新 prompt 恢复
codex exec resume --last "Continue the refactoring from where we left off"

四、成本估算

订阅模式

Plan 月费 Codex 消息 / 5h 适合
Free $0 有限(推广期) 尝试
Go $8 轻量级 偶尔使用
Plus $20 45-225 日常开发
Pro $200 300-1,500 重度使用
Business $25-30/用户 45-225(同 Plus) 团队合规
Enterprise 定制 无固定限制(credits 池) 大企业

5 小时滚动窗口:从首次消息起算,5 小时后重置。不是每日/每月。

API Key 按量计费

API 价格(2026 Q1):

模型 输入 / 1M tokens 输出 / 1M tokens
gpt-5.3-codex ~$1.75 ~$14.00
gpt-5.2-codex $1.25 $10.00
gpt-5-codex-mini $0.25 $2.00

典型任务成本估算

任务类型 输入 tokens 输出 tokens gpt-5.3-codex gpt-5-codex-mini
Code review(PR ~200 行) ~15K ~5K $0.10 $0.02
Bug fix(单文件) ~25K ~10K $0.18 $0.03
Feature 开发(3-5 文件) ~50K ~25K $0.44 $0.06
大型重构(10+ 文件) ~100K ~50K $0.88 $0.13
典型 session(30 分钟) ~60K ~30K $0.53 $0.08

订阅 vs API Break-even 分析

每月 session 数 < 10-15  → API Key 更便宜
每月 session 数 > 15    → Plus ($20/mo) 更划算
每天长 session > 3-4    → Pro ($200/mo) 或考虑 API
仅 CI/CD 不自己写代码    → API Key 更灵活

基础设施成本

场景 规格 月费
Lightsail(最小) 1 vCPU, 2 GB RAM $10
Lightsail(推荐) 2 vCPU, 4 GB RAM $20
EC2 t3.micro(spot) 2 vCPU, 1 GB ~$3-5
EC2 t3.medium(按需) 2 vCPU, 4 GB ~$30
GitHub Actions 免费 2000 分钟/月(公开仓库) $0

总成本示例

场景 月均 API 基础设施 总计/月
CI/CD (GH Actions, 每天 5 PR review) ~$15 $0 ~$15
CI/CD (Lightsail, 每天 10 review + 5 fix) ~$40 $10 ~$50
个人开发 (Plus + 偶尔 CI) $20 $0-10 ~$25
小团队 (Business × 5 + EC2 runner) ~$200 $30 ~$230

五、已知坑点 & 故障排查

5.1 安装相关

问题 原因 解决
EACCES 权限错误 npm 全局安装权限不足 mkdir -p ~/.npm-global && npm config set prefix ~/.npm-global,不要 sudo
Node.js 版本过低 系统包管理器版本过旧 用 NodeSource 或 nvm 安装 Node.js 22+
npm install 时 OOM 低内存实例(< 2 GB) 升级实例或使用 GitHub Releases 预编译二进制
WSL2 中无法访问 Windows 文件系统性能差 项目放 /home/user/ 而非 /mnt/c/

5.2 认证相关

问题 原因 解决
无头服务器无法 OAuth 无浏览器 使用 API Key:export OPENAI_API_KEY=sk-...
OAuth token 过期 默认有效期有限 头环境中用 API Key,非交互模式强制 API Key
API Key 不生效 环境变量未正确设置 echo $OPENAI_API_KEY 验证;放在 ~/.codex/config.toml
API 模型延迟可用 API Key 比订阅晚几周更新模型 关注 OpenAI 公告,或用 ChatGPT 订阅认证

5.3 Sandbox 相关

问题 原因 解决
Operation not permitted bubblewrap/Landlock 阻止了操作 检查 sandbox_mode 设置,需要写权限时用 workspace-write
构建工具无法运行 sandbox 阻止了 /usr/bin 之外的执行 danger-full-access(仅可信环境)
WSL2 中 Sandbox 不工作 WSL2 内核对 bubblewrap 支持有限 升级 WSL2 内核或关闭 sandbox
容器中 sandbox 冲突 Docker 嵌套 sandbox 在 Docker 中运行 Codex 时设置 --sandbox danger-full-access

5.4 运行相关

问题 原因 解决
5 小时窗口耗尽 复杂任务消耗大量消息配额 用更轻量的模型(gpt-5-codex-mini)或升级 plan;复杂任务用 effort: high 减少迭代轮次
Session 数据过大 ~/.codex/sessions/ 未清理 定期清理:find ~/.codex/sessions/ -mtime +30 -delete
codex exec 卡住 无审批策略时遇到需要确认的操作 设置 --approval-policy never
网络超时 OpenAI API 延迟 增加超时:export CODEX_REQUEST_TIMEOUT=300;考虑区域近的部署
Git 仓库检查失败 非 git 目录运行 --skip-git-repo-check 参数

5.5 GitHub Actions 专属

问题 原因 解决
drop-sudo 后后续步骤失败 sudo 权限已被移除且不可逆 需要 sudo 的步骤放新 job
API Key 暴露 硬编码在 workflow YAML 中 必须${{ secrets.OPENAI_API_KEY }}
Codex 输出未获取 未使用 outputs.final-message 给 step 加 id: codex,然后 ${{ steps.codex.outputs.final-message }}
fork PR 无法访问 secrets GitHub 安全限制 pull_request_target 事件(注意安全风险)

5.6 成本相关

问题 原因 解决
API 费用意外飙升 复杂任务消耗 token 远超预期 先用 codex --model gpt-5-codex-mini 试运行;在 prompt 加 effort: minimal
订阅 credits 快速耗尽 cloud tasks 消耗比本地高 3-5x 优先本地执行,仅必要时用 cloud sandbox
Rolling window 不可预测 复杂任务计数远高于简单任务 监控 /usage 命令;复杂重构放在窗口开始时

六、安全最佳实践

1. API Key 管理
   ├── 永远不硬编码在代码/配置文件中
   ├── 使用环境变量或 GitHub Secrets
   └── 不同环境用不同 Key(生产/开发分离)

2. Sandbox 原则
   ├── 默认使用 read-only
   ├── 需要写时才用 workspace-write
   └── danger-full-access 仅在隔离临时环境使用

3. GitHub Actions
   ├── safety-strategy: drop-sudo(默认)
   ├── 公开仓库限制 allow-users
   └── fork PR 用 pull_request_target 时额外审计

4. 成本控制
   ├── CI 高频任务用 gpt-5-codex-mini
   ├── 定时清理 session 数据
   └── 设置 OpenAI 使用上限(usage limits)

七、快速参考卡片

# 安装
npm install -g @openai/codex

# 交互模式
codex                              # 启动 TUI
codex "explain this code"         # 直接提问
codex -m gpt-5.3-codex            # 指定模型

# 无头模式
codex exec "fix failing tests"
codex exec --json --ephemeral "analyze this repo"
codex exec --approval-policy never --sandbox workspace-write "..."

# 恢复会话
codex resume --last
codex resume thr_abc123

# 模型
/mode             # 切换模型(交互模式中)
/model gpt-5.3-codex-spark

# 状态
/status           # 查看当前配置和用量
/usage            # 查看 token 消耗
/compact          # 压缩上下文

# 配置
~/.codex/config.toml    # 主配置文件
AGENTS.md               # 项目指令(项目根目录)

指南完成。数据来源:OpenAI 官方文档、DeepWiki、社区指南、GitHub openai/codex、实测反馈。