You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

同一构建包实现多环境切换(AWS/Docker等)配置方案咨询

Alright, let's solve this problem—ditching those redundant builds and switching environments purely via environment variables is totally doable, especially with your Angular + Nginx + Docker + AWS setup. Below are the exact, tested configuration examples you're requesting, focused on the frontend since that's where the runtime environment switch is trickier.

Frontend: Angular 4 + Nginx + Docker + AWS Elastic Beanstalk

The key here is to move Angular's environment configuration from build-time to run-time. We'll use a dynamic environment file that gets populated with environment variables when the container starts.

1. Angular Dynamic Environment Setup

First, we'll create a template file that will be injected with environment variables at runtime, then update Angular to read from this file instead of static environment files.

Step 1: Create a Runtime Environment Template

Add env.template.js to your src/assets folder:

window.env = {
  apiUrl: '${API_URL}',
  environment: '${ENVIRONMENT}'
};

Step 2: Load the Runtime Environment in index.html

Add this script tag to the <head> section of src/index.html to load the dynamic environment file:

<script src="assets/env.js"></script>

Step 3: Update Angular's Environment Files

Modify your src/environments/environment.ts (and environment.prod.ts if you keep it) to read from the global window.env object:

export const environment = {
  production: window.env.environment === 'production',
  apiUrl: window.env.apiUrl
};

Now Angular will use the runtime values instead of the build-time ones.

2. Dockerfile for Angular

This multi-stage Dockerfile builds the Angular app once, then sets up Nginx with a startup script to inject environment variables.

# Stage 1: Build the Angular app (run once, reuse the image everywhere)
FROM node:14-alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm install --legacy-peer-deps  # Angular 4 might need this for peer dependencies
COPY . .
# Build for production (but we'll override config at runtime)
RUN npm run build --prod

# Stage 2: Serve with Nginx
FROM nginx:alpine
# Copy the built Angular app to Nginx's default web root
COPY --from=builder /app/dist/your-angular-app-name /usr/share/nginx/html
# Copy custom Nginx config
COPY nginx.conf /etc/nginx/nginx.conf
# Copy the environment template
COPY src/assets/env.template.js /usr/share/nginx/html/assets/env.template.js
# Add a startup script to replace environment variables
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

# Run the entrypoint script before starting Nginx
ENTRYPOINT ["/entrypoint.sh"]
CMD ["nginx", "-g", "daemon off;"]

3. Entrypoint Script (entrypoint.sh)

This script replaces placeholders in the environment template with actual environment variables when the container starts:

#!/bin/sh

# Replace placeholders in the template with environment variables
envsubst '${API_URL},${ENVIRONMENT}' < /usr/share/nginx/html/assets/env.template.js > /usr/share/nginx/html/assets/env.js

# Execute the original Nginx command
exec "$@"

4. Nginx Configuration (nginx.conf)

This config ensures Angular routing works correctly and serves the app properly:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    sendfile on;
    keepalive_timeout 65;

    server {
        listen 80;
        server_name localhost;
        root /usr/share/nginx/html;
        index index.html;

        # Handle Angular's client-side routing
        location / {
            try_files $uri $uri/ /index.html;
        }

        # Optional: Reverse proxy to your Spring Boot backend (uncomment if needed)
        # location /api/ {
        #     proxy_pass ${BACKEND_API_URL};
        #     proxy_set_header Host $host;
        #     proxy_set_header X-Real-IP $remote_addr;
        #     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        # }
    }
}

5. Dockerrun.aws.json for Elastic Beanstalk

This file tells AWS EB how to deploy your Docker image and set environment variables. Update the image name and environment values for your setup:

{
  "AWSEBDockerrunVersion": "1",
  "Image": {
    "Name": "your-docker-repo/your-angular-app:latest",
    "Update": "true"
  },
  "Ports": [
    {
      "ContainerPort": "80"
    }
  ],
  "Environment": [
    {
      "Name": "API_URL",
      "Value": "https://qa-backend.yourdomain.com/api"
    },
    {
      "Name": "ENVIRONMENT",
      "Value": "qa"
    }
  ],
  "Logging": "/var/log/nginx"
}

To switch environments (e.g., to production), just update the Value fields in the Environment section and redeploy—no need to rebuild the Docker image.

Backend: Spring Boot + Docker + AWS Elastic Beanstalk

Spring Boot natively supports environment variables, so this is straightforward. You can build a single JAR and configure it via environment variables at runtime:

Dockerfile for Spring Boot

FROM openjdk:8-jdk-alpine
VOLUME /tmp
COPY target/your-spring-boot-app.jar app.jar
# Use environment variables to override Spring properties (e.g., DB config)
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

Dockerrun.aws.json for Backend

Add environment variables for your database and other configs here:

{
  "AWSEBDockerrunVersion": "1",
  "Image": {
    "Name": "your-docker-repo/your-spring-boot-app:latest",
    "Update": "true"
  },
  "Ports": [
    {
      "ContainerPort": "8080"
    }
  ],
  "Environment": [
    {
      "Name": "SPRING_DATASOURCE_URL",
      "Value": "jdbc:postgresql://qa-db.yourdomain.com:5432/your-db"
    },
    {
      "Name": "SPRING_DATASOURCE_USERNAME",
      "Value": "db-user"
    },
    {
      "Name": "SPRING_DATASOURCE_PASSWORD",
      "Value": "db-password"
    }
  ],
  "Logging": "/var/log/spring-boot"
}

With these configurations, you'll only need to build each image once, then deploy to any environment by adjusting environment variables in AWS Elastic Beanstalk. No more redundant builds, which saves time and eliminates inconsistencies between environments.

内容的提问来源于stack exchange,提问作者Gregor Sklorz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:44:54