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
codexsession 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:
npm install -g @openai/codex-cliVerify installation:
codex --version
# Expected: @openai/codex-cli/0.x.xAuthenticate with your OpenAI account:
codex loginThis opens a browser window for OAuth. If you're on a headless server, use the --no-browser flag and copy-paste the URL:
codex login --no-browser
# → Open the printed URL on another device, paste the code backCodex CLI stores credentials in ~/.codex/config.json. You can also use an API key directly:
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:
mkdir my-codex-app && cd my-codex-app
git init
codex initNow run your first prompt:
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:
- Plan the file structure (shows a tree before writing)
- Write all files (FastAPI app, requirements.txt, README.md)
- Run a test (starts the server, hits /health)
- 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:
cd ~/my-existing-project
codexThis 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:
# 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.mdPro tip for large codebases: Use .codex/context.md to give Codex high-level project context that persists across sessions:
# .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:
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:
# .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
Pitfall: Sandbox mode blocks npm install and pip install by default. Whitelist package managers in .codex/sandbox.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):
codex "Deploy this app to Vercel using the Vercel CLI.
Read the VERCEL_TOKEN from environment variable."Railway / Fly.io (full-stack):
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):
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:
# 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
| Pitfall | Symptom | Fix |
|---|---|---|
| Rate limiting | 429 Too Many Requests mid-session | Use --model gpt-4o-mini for simpler tasks. Set CODE_MAX_TOKENS_PER_MINUTE in .codex/config.json |
| Context overflow | Codex "forgets" earlier instructions in long sessions | Break work into smaller sessions. Use --session names to checkpoint. Add project context to .codex/context.md |
| Sandbox blocks install | Error: command 'npm install' blocked by sandbox | Whitelist in .codex/sandbox.json (see Step 4) |
| Git merge conflicts | Codex writes to files you've manually edited | Always git stash before codex sessions. Use codex --diff to review changes before committing |
| API cost spikes | $50+ OpenAI bill after one project | Set 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
| Feature | Codex CLI | Claude Code | Cursor | Copilot |
|---|---|---|---|---|
| Interface | Terminal | Terminal | IDE (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
- Agent workflows: Chain Codex CLI with n8n or Hermes Agent to build autonomous coding pipelines
- Team setup: Read our Runtime Sandboxed Coding Agents Guide for multi-agent collaboration
- Cost optimization: Check out Claude Code + DeepSeek V4 for 90% cheaper alternative
- Mobile coding: If you code on the go, see Codex Mobile Tutorial
Used in this tutorial: OpenAI Codex CLI, Claude Code, n8n, Hermes Agent. Tool mentions are auto-detected by the platform — no manual tagging needed.
相关推荐
Copilot vs Cursor vs Claude Code 2026: Which AI Coder Wins?
Real-world tests, pricing breakdown, and SWE-bench benchmarks for all three AI coding tools
Claude Code After June 15: Complete Migration & Cost Optimization Guide (2026)
Everything Claude Code users need to know about the June 15, 2026 billing restructure — plan selection, cost projections, model tiering, and 6-step optimization strategy.
主题中心
2026 AI 编程工具全景指南
从 Copilot 改版到 Claude Code / DeepSeek 低成本方案——把分散资讯收成可搜索、可对比的工具矩阵。
进入「2026 AI 编程工具全景指南」 →赚钱视角
这个趋势怎么赚钱?
WayToClawEarn 的差异在可验证的赚钱案例,而不只是资讯。从这些复盘开始:
浏览全部案例 →相关教程
相关资讯
- Claude Agent SDK Credit Split June 15: What Claude Code Users Need to Know
- GitHub Copilot AI Credits: Did Your Bill Just Jump 10x? Full Pricing Breakdown, Developer Backlash, and What to Do
- Cursor SDK 3.7: Custom Stores, Custom Tools, Auto-Review, and Nested Subagents Transform It Into an Agent Platform
- Claude Fable 5 Had Invisible Guardrails That Silently Downgraded Responses — Anthropic Apologized and Reversed Course