WayToClawEarn
入门阅读约 30 分钟2026年6月13日

How to Use OpenAI Codex CLI: Build & Deploy Apps from Terminal (2026)

If you want to build and deploy full-stack applications directly from your terminal without opening an IDE, this tutorial walks you through Codex CLI installation, multi-file editing, sandbox-safe execution, and one-command deployment — all in 30 minutes with real code examples.

入门 · 30 分钟 · 2026年6月13日

TL;DR

If you're searching "how to use OpenAI Codex CLI" or "Codex terminal coding agent tutorial," this guide gets you from zero to building and deploying full-stack apps from your terminal in 30 minutes. Codex CLI is OpenAI's terminal-native coding agent — no IDE, no GUI, just a codex command that reads your codebase, understands natural language instructions, and writes/test/debugs code autonomously.

What You'll Learn

  • Install and authenticate Codex CLI on macOS/Linux
  • Run your first codex session and build a working app
  • Use Codex CLI's sandbox mode, multi-file editing, and test loops
  • Deploy directly from Codex CLI to production
  • Avoid the 5 most common pitfalls (rate limits, sandbox escapes, context overflow)

Prerequisites

  • macOS or Linux terminal (Windows via WSL2 works)
  • Node.js 18+ (Codex CLI is an npm package)
  • OpenAI API key or ChatGPT Plus/Pro subscription (Codex CLI uses your OpenAI account)
  • Git installed and configured
  • Basic familiarity with terminal commands

Step 1: Install Codex CLI and Authenticate

Codex CLI ships as an npm package. Install it globally:

terminal
npm install -g @openai/codex-cli

Verify installation:

terminal
codex --version

# Expected: @openai/codex-cli/0.x.x

Authenticate with your OpenAI account:

terminal
codex login

This opens a browser window for OAuth. If you're on a headless server, use the --no-browser flag and copy-paste the URL:

terminal
codex login --no-browser

# → Open the printed URL on another device, paste the code back

Codex CLI stores credentials in ~/.codex/config.json. You can also use an API key directly:

terminal
export OPENAI_API_KEY="sk-..."
codex --api-key "$OPENAI_API_KEY"

Pitfall: Codex CLI requires a ChatGPT Plus, Pro, or Team subscription — free-tier accounts get 403 authentication_required. If you're using API keys, you need at least Tier 1 usage limits.


Step 2: Your First Codex Session

Navigate to an empty project directory and initialize:

terminal
mkdir my-codex-app && cd my-codex-app
git init
codex init

Now run your first prompt:

terminal
codex "Create a Python FastAPI server with three endpoints:
1. GET /health → returns {'status': 'ok'}
2. POST /items → accepts JSON body and stores in a SQLite database
3. GET /items → returns all stored items
Include a requirements.txt and a README.md"

Codex CLI will:

  1. Plan the file structure (shows a tree before writing)
  2. Write all files (FastAPI app, requirements.txt, README.md)
  3. Run a test (starts the server, hits /health)
  4. Report results

Key behavior: Codex CLI works in a plan → execute → verify loop. It won't just dump code — it plans first, asks for confirmation (configurable), then tests its own output.


Step 3: Multi-File Editing and Iterative Development

Codex CLI's real power is multi-file context awareness. Start a session in an existing project:

terminal
cd ~/my-existing-project
codex

This enters interactive mode. The prompt > prefix indicates Codex is ready:

> Add TypeScript types for all API responses and update the client code to use them

Codex reads your entire codebase (respecting .gitignore), identifies all files that need changes, and applies them coherently.

Session management:

terminal

# Start named session (resumable)
codex --session "add-auth"

# Resume previous session
codex --resume

# List sessions
codex sessions list

# Export session as a summary
codex sessions export add-auth > changes.md

Pro tip for large codebases: Use .codex/context.md to give Codex high-level project context that persists across sessions:

markdown

# .codex/context.md
This is a Next.js 14 e-commerce app with App Router.
Backend: Supabase (PostgreSQL + Auth).
State management: Zustand.
Styling: Tailwind CSS.
Testing: Vitest + Playwright.
CI: GitHub Actions.

Step 4: Sandbox Mode and Safety

Codex CLI has a built-in sandbox mode that prevents file writes outside the project directory:

terminal
codex --sandbox "Refactor all API calls to use a shared http client"

Sandbox mode restrictions:

  • No writes outside the project root
  • No network calls to unapproved domains (configurable in .codex/sandbox.json)
  • No shell commands that modify system state (rm -rf /, chmod, etc.)

For CI/CD pipelines, always use sandbox mode:

yaml

# .github/workflows/codex-review.yml
name: Codex Code Review
on: [pull_request]
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm install -g @openai/codex-cli
      - run: |
          codex --sandbox --non-interactive \
            "Review this PR diff for bugs, security issues, and code style violations.
             Output a markdown report to codex-review.md"
      - uses: actions/upload-artifact@v4
        with:
          name: codex-review
          path: codex-review.md

Codex CLI sandbox configuration

Pitfall: Sandbox mode blocks npm install and pip install by default. Whitelist package managers in .codex/sandbox.json:

json
{
  "allowed_commands": ["npm install", "npm ci", "pip install", "cargo build"],
  "allowed_domains": ["registry.npmjs.org", "pypi.org"]
}

Step 5: Deploy from Codex CLI

Codex CLI can deploy directly to common platforms:

Vercel (Next.js / frontend):

terminal
codex "Deploy this app to Vercel using the Vercel CLI.
Read the VERCEL_TOKEN from environment variable."

Railway / Fly.io (full-stack):

terminal
codex "Generate a fly.toml config, build a Dockerfile, and deploy to Fly.io.
Use the FLY_API_TOKEN from environment."

GitHub Pages (static sites):

terminal
codex "Build the static output and deploy to GitHub Pages using
the gh-pages npm package. Auto-detect the repo URL from git remote."

The deployment loop:

terminal

# 1. Build and test
codex --sandbox "Run the full test suite and fix any failures"

# 2. If all green, deploy
codex "Tests pass. Deploy to production on Railway."

Common Pitfalls and Fixes

PitfallSymptomFix
Rate limiting429 Too Many Requests mid-sessionUse --model gpt-4o-mini for simpler tasks. Set CODE_MAX_TOKENS_PER_MINUTE in .codex/config.json
Context overflowCodex "forgets" earlier instructions in long sessionsBreak work into smaller sessions. Use --session names to checkpoint. Add project context to .codex/context.md
Sandbox blocks installError: command 'npm install' blocked by sandboxWhitelist in .codex/sandbox.json (see Step 4)
Git merge conflictsCodex writes to files you've manually editedAlways git stash before codex sessions. Use codex --diff to review changes before committing
API cost spikes$50+ OpenAI bill after one projectSet CODE_MAX_TOKENS_PER_REQUEST=8000 and CODE_MODEL=gpt-4o-mini for non-critical tasks. Codex uses ~50K tokens per average session with GPT-4o

Codex CLI vs Other AI Coding Tools

FeatureCodex CLIClaude CodeCursorCopilot
InterfaceTerminalTerminalIDE (VS Code fork)IDE extension
Multi-file edits✅ Yes✅ Yes✅ Yes⚠️ Limited
Sandbox mode✅ Built-in⚠️ Via containers❌ No❌ No
CI/CD ready--non-interactive✅ Yes❌ No❌ No
Session resume✅ Named sessions✅ Yes❌ No❌ No
Cost (per session)$0.50-3.00$1-5$20/mo flat$10-39/mo

Codex CLI's key differentiator is headless/CI-ready operation — no IDE required, making it ideal for automated workflows, pre-commit hooks, and CI pipelines.


Next Steps


Used in this tutorial: OpenAI Codex CLI, Claude Code, n8n, Hermes Agent. Tool mentions are auto-detected by the platform — no manual tagging needed.

免责声明:本站案例均为知识分享内容,仅供灵感与参考,不构成收益承诺;由此进行的外部执行与结果请自行判断并承担相应责任。

相关推荐