Solucionado (ver solução)
Solucionado
(ver solução)
7
respostas

Erro ao rodar o Docker

Após rodar o comando que inicia o Docker o Spring Boot é inicializado e retorna o seguinte erro:

2020-11-12 01:17:44.415 WARN 1 --- [gistrationTask1] d.c.b.a.c.r.ApplicationRegistrator : Failed to register application as Application(name=spring-boot-application, managementUrl=http://50d3d26540dc:8080/actuator, healthUrl=http://50d3d26540dc:8080/actuator/health, serviceUrl=http://50d3d26540dc:8080/) at spring-boot-admin ([http://localhost:8081/instances]): I/O error on POST request for "http://localhost:8081/instances": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused). Further attempts are logged on DEBUG level

Quando tento realizar a requisição no endpoint "/topicos" me retorna o seguinte:

{
    "timestamp": "2020-11-12T01:12:55.618+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "",
    "path": "/topicos"
}

Não sei se o erro retornado ao inicializar o Spring Boot tem a ver com o Unauthorized, alguém pode dar um help por favor?

7 respostas

Oi Iuri

O container não conseguiu conectar ao banco de dados, envia aqui o comando "docker run" com as variáveis de ambiente que você usou para subir o container, por favor.

Aqui está

docker run -p 8080:8080 -e SPRING_PROFILES_ACTIVE='prod' -e FORUM_DATABASE_URL='jdbc:h2:mem:alura-forum' -e FORUM_DATAB
ASE_USERNAME='sa' -e FORUM_DATABASE_PASSWORD='' -e FORUM_JWT_SECRET='123456' alura/forum

Seu comando docker-run parece correto

 at spring-boot-admin ([http://localhost:8081/instances]): I/O error on POST request for "http://localhost:8081/instances": Connection refused 

Pela mensagem de erro acima, você subiu o spring-boot-admin na porta 8081?

O arquivo application-prod.properties está com a seguinte configuração:

# spring boot admin server
spring.boot.admin.client.url=http://localhost:8081

o arquivo de configuração está igual ao do professor.

Oi Iuri,

Parece que subiu normalmente o Spring Boot com o Docker, mas alguma configuração de segurança está estranha, pois não deveria dar 401 ao acessar o /topicos.

Posta aqui o código das suas classes de configuração de segurança.

Bom dia,

Aqui está o código da classe SecurityConfigurations


@EnableWebSecurity
@Configuration
@Profile(value = {"prod", "test"})
public class SecurityConfigurations extends WebSecurityConfigurerAdapter {

    @Autowired
    private AutenticacaoService autenticacaoService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UsuarioRepository usuarioRepository;

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    //Configuracoes de autenticacao
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(autenticacaoService).passwordEncoder(new BCryptPasswordEncoder());
    }

    //Configuracoes de autorizacao
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers(HttpMethod.GET, "/topicos").permitAll()
        .antMatchers(HttpMethod.GET, "/topicos/*").permitAll()
        .antMatchers(HttpMethod.POST, "/auth").permitAll()
        .antMatchers(HttpMethod.GET, "/actuator/**").permitAll()
        .antMatchers(HttpMethod.DELETE, "/topicos/*").hasRole("MODERADOR")
        .anyRequest().authenticated()
        .and().csrf().disable()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().addFilterBefore(new AutenticacaoViaTokenFilter(tokenService, usuarioRepository), UsernamePasswordAuthenticationFilter.class);
    }


    //Configuracoes de recursos estaticos(js, css, imagens, etc.)
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/**.html", "/v2/api-docs", "/webjars/**", "/configuration/**", "/swagger-resources/**");
    }

}
solução!

Resolvi o problema, quando eu rodo o comando docker-run no intellij não funcionava, rodei o comando no cmd como administrador e a aplicação voltou a funcionar. Muito obrigado pelo empenho em me ajudar pessoal!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software