GVKun编程网logo

无法从外部Docker容器访问SpringBoot @RestController(docker容器无法访问外部网络)

12

在这篇文章中,我们将带领您了解无法从外部Docker容器访问SpringBoot@RestController的全貌,包括docker容器无法访问外部网络的相关情况。同时,我们还将为您介绍有关Fire

在这篇文章中,我们将带领您了解无法从外部Docker容器访问SpringBoot @RestController的全貌,包括docker容器无法访问外部网络的相关情况。同时,我们还将为您介绍有关Firefox(无头)+ Selenium无法从Docker容器访问Internet、java – 如何在Springboot Restcontroller中使用PUT方法?、JSR-使用Spring Boot对Spring @RestController进行349 bean验证、linux – 无法从外部机器访问公开暴露的Docker容器端口,只能从localhost访问?的知识,以帮助您更好地理解这个主题。

本文目录一览:

无法从外部Docker容器访问SpringBoot @RestController(docker容器无法访问外部网络)

无法从外部Docker容器访问SpringBoot @RestController(docker容器无法访问外部网络)

tl; dr一个RestController如果在Docker容器中运行,则可以正确回答,而另一个则不能。

该服务有两个API alive

@CrossOrigin(origins = "*", maxAge = 3600)@RestControllerpublic class AliveController {    @RequestMapping(value = "/alive", method = RequestMethod.GET)    public ResponseEntity<?> alive() {        return new ResponseEntity<>(HttpStatus.OK);    }}

callcount

@CrossOrigin@RestControllerpublic class CallController {    private static int callCount = 0;    @RequestMapping(value = "/callcount", method = RequestMethod.GET)    public ResponseEntity<?> callCount() {        return new ResponseEntity<>(++callCount, HttpStatus.OK);    }}

它们都通过docker-compose运行。

version: ''2''services:  service:    image: my/service    ports:      - "4000:4000"

docker-machine ip返回192.168.99.100

alive返回一个空的200响应。如预期的那样。

$ curl -i http://192.168.99.100:4000/aliveHTTP/1.1 200Content-Length: 0Date: Mon, 22 Aug 2016 17:33:58 GMT

callcount应该返回200响应,并且每次调用API时数字都会增加。可悲的是事实并非如此。

$ curl -i http://192.168.99.100:4000/callcountHTTP/1.1 404Content-Type: application/hal+json;charset=UTF-8Transfer-Encoding: chunkedDate: Mon, 22 Aug 2016 17:37:26 GMT{"timestamp":1471887446871,"status":404,"error":"Not Found","message":"No message available","path":"/callcount"}

在本地运行服务可提供预期的结果。

$ curl -i http://localhost:4000/callcountHTTP/1.1 200Content-Type: application/json;charset=UTF-8Transfer-Encoding: chunkedDate: Mon, 22 Aug 2016 17:43:40 GMT1

maven-spotify插件用于根据以下内容创建映像Dockerfile

FROM java:8EXPOSE 4000VOLUME /tmpADD service*.jar app.jar# http://stackoverflow.com/a/33882286/1309035# Without this, Java uses /dev/random to seed its SecureRandom class, which can cause Java code to block unexpectedly.ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom","-jar","app.jar"]

我使用的是最新的Docker和Docker-Compose版本(2016年8月22日下载)。

解决了 !请参阅下面的更新部分。找到最终答案后将确定问题。- 问题 :为什么callcount无法从Docker容器外部访问?

进一步尝试:

  • @CrossOrigin(origins = "*", maxAge = 3600) -同样的结果
  • spring文档中的全局CORS配置。
  • 将两个方法合并到AliveController中。
  • 删除了每个容器和映像,并从头开始重新构建了docker。

Udates

callcountAPI未由Spring注册。我添加了另一个testAPI来验证这一点,它也无法通过curl访问。alive仍然可以正常工作并显示在日志中。

bash-3.2$ docker logs asmstack_service_1 | grep callcountbash-3.2$ docker logs asmstack_service_1 | grep testbash-3.2$ docker logs asmstack_service_1 | grep alive2016-08-23 08:42:06.530  INFO 1 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/alive],methods=[GET]}" onto public org.springframework.http.ResponseEntity<?> de.bahr.asmstack.AliveController.alive()

我在本地使用JDK 1.8(java.vm.vendor = Oracle Corporation)。

$ java -versionjava version "1.8.0_74"Java(TM) SE Runtime Environment (build 1.8.0_74-b02)Java HotSpot(TM) 64-Bit Server VM (build 25.74-b02, mixed mode)

启动方法之间的差异

使用callcountIntelliJ和以外的方式运行应用程序时,已正确注册mvn spring-boot:run。如果运行,它不会被注册

java -Djava.security.egd=file:/dev/./urandom -jar my-service.jar 要么

java -jar my-service.jar。这应该是为什么不能从Docker容器中访问它的原因。

知道为什么会这样吗? 从2015年末开始,它在另一个项目中的运作方式就与之类似。

答案1

小编典典

我可以在@ daniel.eichten和@ShawnClark的帮助下解决问题,但是我不明白 为什么 它会失败/起作用。Ť

这不是Docker问题,而是Spring问题。

@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

@EnableAutoConfiguration@EnableWebMvc@Configuration@ComponentScanpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

现在,即使在Docker容器中运行时,也可以按预期访问所有API。

Firefox(无头)+ Selenium无法从Docker容器访问Internet

Firefox(无头)+ Selenium无法从Docker容器访问Internet

如何解决Firefox(无头)+ Selenium无法从Docker容器访问Internet?

我已经通过C测试了Internet连接,并且该连接是在docker内部工作的。但是,当我运行带有硒python绑定的无头firefox时,硒穿过A

B

但是当我从主机运行相同的python文件时,它运行得很好。

(请不要建议我使用docker-selenium映像。我有理由不使用它们。除更改基本映像外,欢迎任何建议或查询。)

下面是run.py:

wget https://www.google.com

以下是Dockerfile:

TimeoutException

我的容器构建和运行命令是:

>> docker run myselcontainer

Traceback (most recent call last):
  File "run.py",line 24,in <module>
    driver = webdriver.Firefox(service_log_path=os.devnull,options=options,capabilities=capabilities,firefox_profile=profile)
  File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/firefox/webdriver.py",line 170,in __init__
    RemoteWebDriver.__init__(
  File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py",line 157,in __init__
    self.start_session(capabilities,browser_profile)
  File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py",line 252,in start_session
    response = self.execute(Command.NEW_SESSION,parameters)
  File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py",line 321,in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py",line 242,in check_response
    raise exception_class(message,screen,stacktrace)
selenium.common.exceptions.TimeoutException: Message: Connection refused (os error 111)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

java – 如何在Springboot Restcontroller中使用PUT方法?

java – 如何在Springboot Restcontroller中使用PUT方法?

我正在使用Spring boot开发一个应用程序.我尝试了所有表示动词,如GET,POST,DELETE都可以正常工作.通过使用PUT方法,它不支持弹簧启动.我是否需要添加任何新配置.

Put方法只能处理请求没有任何参数.如果我添加任何查询参数或表单数据,它不起作用.请任何专业人士帮助我解决这个问题.

@RequestMapping("/student/info")
@RequestMapping(method = RequestMethod.PUT)
public @ResponseBody String updateStudent(@RequestParam(value = "stdName")String stdName){
    LOG.info(stdName);
    return "ok";
}

Request method ‘PUT’ not supported

最佳答案
这段代码可以正常工作.您必须在类级别或函数中指定请求映射
水平.

@RequestMapping(value = "/student/info",method = RequestMethod.PUT)
public @ResponseBody String updateStudent(@RequestBody Student student){
 LOG.info(student.toString());
 return "ok";
}

JSR-使用Spring Boot对Spring @RestController进行349 bean验证

JSR-使用Spring Boot对Spring @RestController进行349 bean验证

我正在使用Spring Boot
1.5.2.RELEASE,并且无法为@RequestParam@PathVariableat方法本身合并JSR-349(bean验证1.1)。

对于POST请求,如果方法参数是Java
POJO,则使用对该参数进行注释@Valid可以正常工作,但使用@RequestParam@PathVariable进行注释@NotEmpty,则@Email不能正常工作。

我已经用Spring注释了控制器类 @Validated

Spring Boot包括- validation-api-1.1.0.Final.jarhibernate-validator-5.3.4.Final.jar

我有什么想念的吗?

示例代码

@RequestMapping(method = RequestMethod.GET, value = "/testValidated", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseBean<String> testValidated(@Email @NotEmpty @RequestParam("email") String email) {    ResponseBean<String> response = new ResponseBean<>();    response.setResponse(Constants.SUCCESS);    response.setMessage("testValidated");    logger.error("Validator Not called");    return response; }

当我发送空值或格式不正确的电子邮件地址时,永远不会调用下面的处理程序,并且email控制权始终与in testValidated方法一起使用。

@ExceptionHandler(ConstraintViolationException.class)@ResponseBody@ResponseStatus(HttpStatus.BAD_REQUEST)public ResponseBean handle(ConstraintViolationException exception) {    StringBuilder messages = new StringBuilder();    ResponseBean response = new ResponseBean();    exception.getConstraintViolations().forEach(entry -> messages.append(entry.getMessage() + "\n"));    response.setResponse(Constants.FAILURE);    response.setErrorcode(Constants.ERROR_CODE_BAD_REQUEST);    response.setMessage(messages.toString());    return response;}

ResponseBean<T> 是我的应用程序特定的类。

答案1

小编典典

经过两天以上的成功命中和审判,我问了这个问题。由于对Spring验证和JSR验证,Spring如何调用JSR验证器,JSR标准中的更改以及所支持的验证类型感到困惑,因此出现了许多令人困惑的答案。

最后,这篇文章对我们很有帮助。

我分两步解决了问题,

1.在我的豆子中添加了以下豆子Configuration-没有这些豆子,将无法正常工作。

@Beanpublic MethodValidationPostProcessor methodValidationPostProcessor() {    MethodValidationPostProcessor mvProcessor = new MethodValidationPostProcessor();    mvProcessor.setValidator(validator());    return mvProcessor;}@Beanpublic LocalValidatorFactoryBean validator() {    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();    validator.setProviderClass(HibernateValidator.class);    validator.afterPropertiesSet();    return validator;}

2.将Spring的@Validated注释放置在我的控制器上,如下所示,

@RestController@RequestMapping("/...")@Validatedpublic class MyRestController {}

验证为- org.springframework.validation.annotation.Validated

此设置不会影响在同一控制器中@Valid进行@RequestBody验证的注释,并且注释仍将继续工作。

因此,现在,我可以针对MyRestController类中的方法触发以下验证,

@RequestMapping(method = RequestMethod.GET, value = "/testValidated" , consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseBean<String> testValidated(        @Email(message="email RequestParam is not a valid email address")         @NotEmpty(message="email RequestParam is empty")         @RequestParam("email") String email) {    ResponseBean<String> response = new ResponseBean<>();    ....    return response; }

我必须在异常处理程序中添加另一个处理程序以处理异常-
ConstraintViolationException尽管由于在@Validated抛出时@Valid会抛出此异常MethodArgumentNotValidException

linux – 无法从外部机器访问公开暴露的Docker容器端口,只能从localhost访问?

linux – 无法从外部机器访问公开暴露的Docker容器端口,只能从localhost访问?

我在我的Ubuntu Linux 14.04计算机上运行了一个Docker容器,公开了一个端口:
docker run --name spacyapi -d -p 127.0.0.1:7091:7091 jgontrum/spacyapi:en

我可以连接并执行容器中服务器的命令,而不会出现本地机器的问题.例如:

curl http://localhost:7091/api --header 'content-type: application/json' --data '{"text": "This is a test."}' -X POST

该命令忠实执行.但是,如果我从外部机器尝试相同的CURL命令,我会收到“连接被拒绝”错误:

curl http://192.5.169.50:5000/api --header 'content-type: application/json' --data '{"text": "This is a test."}' -X POST
curl: (7) Failed to connect to 192.5.169.50 port 7091: Connection refused

其中192.5.169.50是运行Docker容器的框的IP地址.

我认为我不需要任何iptables规则,因为我不需要在同一个盒子上运行Node.JS服务器.我本地网络上的所有其他计算机都可以正常访问Node.JS服务器.但不是Docker容器充当服务器.

我怎样才能解决这个问题?

解决方法

您没有使用此标志公开发布您的端口:
-p 127.0.0.1:7091:7091

该标志表示要在主机127.0.0.1接口(localhost),端口7091上发布到容器端口7091.到达该端口的唯一方法是在主机上并连接到环回接口.

要公开发布端口,请从该标志中删除IP:

-p 7091:7091

或显式发布到所有接口:

-p 0.0.0.0:7091:7091

后一种格式与第一种格式相同,只要您没有使用dockerd –ip x.x.x.x覆盖docker守护程序设置或在/etc/docker/daemon.json文件中设置ip值.

今天关于无法从外部Docker容器访问SpringBoot @RestControllerdocker容器无法访问外部网络的介绍到此结束,谢谢您的阅读,有关Firefox(无头)+ Selenium无法从Docker容器访问Internet、java – 如何在Springboot Restcontroller中使用PUT方法?、JSR-使用Spring Boot对Spring @RestController进行349 bean验证、linux – 无法从外部机器访问公开暴露的Docker容器端口,只能从localhost访问?等更多相关知识的信息可以在本站进行查询。

本文标签: