Моя настройка: Отдельные эластичные c экземпляры beanstalk для Angular внешнего интерфейса, Springboot и MongoDB.
Angular 8 (Tomcat с Nginx прокси сервер) Следующие два файла включены в .ebextensions (правильно загружены)
nginx -proxy.config
option_settings:
aws:elasticbeanstalk:environment:proxy:
ProxyServer: nginx
nginx. conf
user nginx;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
worker_processes auto;
worker_rlimit_nofile 33282;
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" "$http_host"';
include conf.d/*.conf;
map $http_upgrade $connection_upgrade {
default "upgrade";
}
server {
listen 80 default_server;
#listen [::]:80 default_server; #Not sure if I need this.
server_name domain.com www.domain.com; #What should this be? Default is _
if ($http_x_forwarded_proto = 'http'){
return 301 https://$host$request_uri; #To force HTTPs
}
location / {
root /var/lib/tomcat8/webapps/ROOT;
try_files $uri /index.html; #To fix 404s on refresh
}
location /api {
proxy_pass http://AWS_Public_DNS_of_SpringBoot_Backend:5000; #Nginx listens on port 5000...
proxy_http_version 1.1;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Host $host;
#proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#proxy_cache_bypass $http_upgrade;
#proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header X-Forwarded-Proto $scheme;
}
access_log /var/log/nginx/access.log main;
client_header_timeout 60;
client_body_timeout 60;
keepalive_timeout 60;
gzip off;
gzip_comp_level 4;
# Include the Elastic Beanstalk generated locations
include conf.d/elasticbeanstalk/01_static.conf;
include conf.d/elasticbeanstalk/healthd.conf;
}
}
Angular 8 environment.prod.ts
export const environment = {
production: true,
SAMPLE_API_ENDPOINT: 'https://example.com/api/...'
}
Angular 8 рабочая сборка
ng build --prod --aot
Springboot WebSecurityConfig. java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.httpBasic().disable()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/auth/login").permitAll() // Login end-point
.antMatchers("/api/auth/register").permitAll()
.and()
.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint())
.and()
.apply(new JwtConfigurer(jwtTokenProvider))
.and()
.requiresChannel()
.requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null)
.requiresSecure();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
//Not entirely certain which ports requests are coming from...
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200", "https://example.com:5000", "https://example.com:443", "https://example.com", "https://example.com:80", "https://example.com:8080"));
configuration.setAllowCredentials(true);
configuration.setExposedHeaders(Arrays.asList("Content-Type", "Cache-Control"));
configuration.setAllowedHeaders(Arrays.asList(
"Access-Control-Allow-Headers","Access-Control-Allow-Origin","Access-Control-Request-Method",
"Access-Control-Request-Headers", "Origin", "Cache-Control", "Content-Type", "Authorization"
)
);
configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT", "OPTIONS"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
Springboot application-prod.properties
server.port=5000
Springboot gradle build
./gradlew bootJar -Dspring.profiles.active=prod
AWS Свойства конфигурации экземпляра EBS Springboot
SERVER_PORT = 5000
SPRING_PROFILES_ACTIVE = prod
AWS EBS Springboot Security Группа
Inbound: 80, 8080, 5000, 4200, 443 (Angular Application Security Group ID sg-06e...)
Проблемы, с которыми я до сих пор сталкивался: Проблемы с COR (думаю, я решил это, но мне нужно закрыть разрешенные источники для указания c портов ) Тайм-аут проблемы (я с tarted изменение nginx настроек конфигурации, что привело меня к ...) Слишком много перенаправлений (где я сейчас нахожусь).
- У меня есть inte rnet классовая отделка c балансировщик нагрузки на Angular приложениях с конфигурациями портов:
**80 (HTTP) forwarding to 80 (HTTP)**
**443 (HTTPS, ACM Certificate: f86...) forwarding to 80 (HTTP)**
- Все экземпляры являются частью одного и того же VP C
- У меня есть elasti c IP-адреса, связанные как с Angular приложениями, так и с экземплярами Springboot
Я абсолютно уверен, что мой вся установка - это большой беспорядок, поэтому мне нужен совет, как это убрать. Прежде всего, мне нужно знать, какие порты мне следует исключить, нужен ли мне балансировщик нагрузки (или если есть лучший метод) и если elasti c IP необходимы как на передней части, так и на внутренней стороне. (примечание: у меня есть экземпляр Mon go DB ec2, который уже обменивается данными с бэкэндом Springboot. Экземпляр Mon go не имеет elasti c IP ... это нужно?). Я также хочу знать, как я могу поддерживать https от внешнего интерфейса до внутреннего (нужно ли создавать отдельный сертификат SSL для Springboot?) И, наконец, я не знаю, нужна ли какая-либо конфигурация для Tomcat, чтобы разрешить связь между Angular с прокси-сервером Nginx и springboot.
Моя проблема в том, что я не могу установить связь между приложением angular и бэкэндом springboot. I перепробовал много вещей, но я добился незначительного прогресса в достижении успеха.