如何通过Docker运行Stripe CLI并转发请求至本地端点
问题:Docker运行Stripe CLI转发请求至本地域名后容器自动退出
背景
公司环境中Stripe CLI被病毒检测工具拦截,无法直接安装使用。需要通过Docker容器运行Stripe CLI,并将Webhook请求转发至主机上的本地域名端点 example.local/stripe_endpoint.php。尝试通过自定义entrypoint修改容器hosts文件指向本地IP,但容器完成Stripe登录后随即退出,无法持续运行。
当前使用的配置
Dockerfile
# Use the official Stripe CLI image as the base image FROM stripe/stripe-cli:latest # Set environment variables ENV STRIPE_SECRET_KEY=... # Copy the entrypoint script into the container COPY entrypoint.sh /entrypoint.sh # Make the entrypoint script executable RUN chmod +x /entrypoint.sh # Set the entrypoint command ENTRYPOINT ["/bin/sh", "/entrypoint.sh"]
docker-compose.yml
version: '3' services: stripe_cli: build: context: . dockerfile: Dockerfile networks: - my_bridge container_name: stripe_cli_container working_dir: /app networks: my_bridge: driver: bridge
entrypoint.sh
# Configure custom DNS resolution echo '0.0.0.0 example.local' >> /etc/hosts # Start the Stripe CLI with your desired command /bin/sh -c "stripe listen --forward-to http://example.local/stripe_endpoint.php && tail -f /dev/null"
注:0.0.0.0 实际为本地主机IP,已做模糊处理
问题分析
容器自动退出的核心原因有两个:
- Hosts配置错误:将
example.local指向0.0.0.0会让容器将请求转发到自身而非主机,导致stripe listen无法连接到目标端点,进程启动失败后直接退出,后续的tail -f /dev/null根本无法执行。 - 脚本执行逻辑缺陷:即使
stripe listen正常启动,使用&&串联命令意味着只有当前者成功执行完成后才会运行后者,但stripe listen是前台持续运行的进程,只有它崩溃退出时才会触发tail,而如果启动失败则直接终止容器。
解决思路
1. 修正Hosts解析,确保容器能访问主机端点
不要手动修改/etc/hosts,直接通过Docker的extra_hosts参数配置域名解析,将example.local指向主机在Docker网络中的可达IP:
- 对于Docker Desktop(Windows/macOS),可以使用内置的
host.docker.internal作为主机IP; - 对于Linux环境,填写主机的局域网IP(如
192.168.1.100)。
2. 简化配置,移除自定义Entrypoint和Dockerfile
直接使用官方镜像,通过docker-compose配置环境变量、命令和hosts映射,避免不必要的自定义脚本:
version: '3' services: stripe_cli: image: stripe/stripe-cli:latest environment: - STRIPE_SECRET_KEY=your_actual_secret_key command: listen --forward-to http://example.local/stripe_endpoint.php extra_hosts: - "example.local:host.docker.internal" # 替换为你的主机IP或host.docker.internal volumes: - ~/.config/stripe:/root/.config/stripe # 挂载本地登录凭证,避免容器每次启动都需要登录 networks: - my_bridge container_name: stripe_cli_container networks: my_bridge: driver: bridge
3. 验证端点可达性
启动容器前,先进入临时容器测试主机端点是否可访问:
docker run --rm --extra-hosts "example.local:host.docker.internal" curlimages/curl http://example.local/stripe_endpoint.php
如果返回正常响应,说明网络配置没问题;如果返回连接失败,检查主机防火墙是否允许Docker网络访问该端口,或端点是否正常运行。
4. 确保Stripe CLI已登录
如果本地环境允许临时运行Stripe CLI一次,执行stripe login完成登录,凭证会保存在~/.config/stripe目录,通过挂载该目录到容器,即可让容器复用登录状态,无需每次启动都进行交互式登录。
内容的提问来源于stack exchange,提问作者user16861522
相关产品推荐
相关产品推荐

