如何在docker-compose文件中将links替换为depends_on?
Hey there! Let's fix that deprecated links config in your Docker Compose file and swap it out for the recommended depends_on—it's simpler and aligns with current Docker best practices.
First, a quick background: links was phased out because Docker Compose now automatically creates a dedicated bridge network for your project by default. On this network, every service name acts as a resolvable hostname, so you don't need the alias mapping that links provided. depends_on takes care of the startup dependency order instead.
Here's your updated, fully functional docker-compose.yml
I've filled in the missing parts for your Node.js and PHP services and replaced the links with proper depends_on setup:
version: "3.1" services: nginx: image: nginx:alpine ports: - "8000:80" volumes: - ./php/content:/srv/www/content - ./static:/srv/www/static - ./nginx/default.conf:/etc/nginx/conf.d/default.conf # Replace deprecated links with depends_on to define startup order depends_on: - node-app - php-api # Pro tip: In Nginx's default.conf, use the service names as hostnames! # Example: proxy_pass http://node-app:3000; or fastcgi_pass php-api:9000; node-app: image: node:18-alpine volumes: - ./node-app:/app working_dir: /app command: npm start # Add depends_on here if this service relies on another (e.g., a database) php-api: image: php:8.2-fpm-alpine volumes: - ./php/content:/srv/www/content # Same here—add depends_on if you have a database or other dependencies
Key things to keep in mind
depends_ononly manages startup order: It ensuresnode-appandphp-apistart before Nginx, but it won't wait for those services to be fully ready (e.g., Node.js finishing its init, PHP-FPM accepting connections). If you need to wait for readiness, addhealthcheckto your services and usecondition: service_healthyindepends_on, like this:depends_on: php-api: condition: service_healthy- Update your Nginx config: If you were using the alias from
links(likephp-a), replace that with the service name (php-api) in your Nginx upstream definitions—this works because of the default Compose network's DNS resolution. - No more aliases needed: If you relied on
linksto create custom host aliases, you can define them in a custom network'saliasessection, but in most cases, using the service name directly is cleaner.
内容的提问来源于stack exchange,提问作者François Romain
相关产品推荐
相关产品推荐

