[Bug]Error from server (BadRequest): container “xx“ in pod “xx“ is waiting to start:trying and faili

在尝试通过yaml文件创建Kubernetes Pod时遇到错误,报错提示为尝试并失败拉取最新镜像。实际上,本地已经存在所需镜像。为避免这种情况,需要在yaml文件中为每个容器设置`imagePullPolicy`为`IfNotPresent`,确保使用已存在的本地镜像。更新yaml文件后,Pod状态恢复正常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

0 背景

执行如下yaml文件创建Pod时发生报错

---
apiVersion: v1
kind: Pod
metadata:
  name: volume-pod
spec:
  containers:
    - name: tomcat
      image: tomcat:latest
      ports:
        - containerPort: 8080
      volumeMounts:
        - name: app-logs
          mountPath: /usr/local/tomcat/logs
    - name: busybox
      image: busybox:latest
      command: ["sh","-c","tail -f /logs/catalina*.log"]
      volumeMounts:
      - name: app-logs
        mountPath: /logs
  volumes:
    - name: app-logs
      emptyDir: {}

1 报错

Error from server (BadRequest): container “tomcat” in pod “volume-pod” is waiting to start: trying and failing to pull image
在这里插入图片描述
Error from server (BadRequest): container “tomcat” in pod “volume-pod” is waiting to start: trying and failing to pull image
在这里插入图片描述
但是在本地存在镜像
在这里插入图片描述
需要在Pod的yaml文件中设置参数( imagePullPolicy: IfNotPresent),避免k8s去拉取最新的镜像

---
apiVersion: v1
kind: Pod
metadata:
  name: volume-pod
spec:
  containers:
    - name: tomcat
      image: tomcat:latest
      imagePullPolicy: IfNotPresent
      ports:
        - containerPort: 8080
      volumeMounts:
        - name: app-logs
          mountPath: /usr/local/tomcat/logs
    - name: busybox
      image: busybox:latest
      imagePullPolicy: IfNotPresent
      command: ["sh","-c","tail -f /logs/catalina*.log"]
      volumeMounts:
      - name: app-logs
        mountPath: /logs
  volumes:
    - name: app-logs
      emptyDir: {}

重新生成pod,发现状态已经正常
在这里插入图片描述

### 解决 `urllib.error.HTTPError` HTTP Error 400 Bad Request HTTP Error 400 表示客户端发送的请求存在语法错误或无法被服务器理解。这种错误通常由以下几个原因引起: #### 原因分析 1. **URL 不正确** 如果 URL 中包含非法字符或者拼写错误,可能会导致服务器无法解析该请求[^1]。 2. **请求头不合法** 请求头可能缺少必要的字段(如 Content-Type),或者包含了不符合服务器预期的内容[^2]。 3. **数据编码问题** POST 数据未按照正确的格式进行编码,尤其是涉及特殊字符时,可能导致服务器拒绝处理请求[^2]。 4. **参数传递错误** 参数名称或值存在问题,比如某些字符未经适当转义,也可能引发此错误[^2]。 #### 解决方案 以下是针对上述常见原因的具体解决方案: ##### 1. 验证并修正 URL 确保目标 URL 是有效的,并且所有路径分隔符 `/` 和查询字符串 `?` 后面的部分均经过适当编码。可以使用 Python 的 `urllib.parse.quote()` 方法来对 URL 或其部分组件进行编码: ```python from urllib.parse import quote_plus url = f"http://example.com/api?key={quote_plus('special value with spaces')}" print(url) ``` ##### 2. 设置合适的请求头 对于 POST 请求,需指定正确的 `Content-Type` 头部信息。如果提交 JSON 格式的数据,则应设置为 `application/json`;如果是表单数据,则设为 `application/x-www-form-urlencoded`。 ```python import json from urllib.request import Request, urlopen headers = { 'Content-Type': 'application/json', } data = {'key': 'value'} json_data = json.dumps(data).encode('utf-8') req = Request('http://example.com/api', data=json_data, headers=headers) response = urlopen(req) body = response.read().decode() print(body) ``` ##### 3. 正确编码 POST 数据 POST 数据应当依据实际需求采用恰当的方式编码。例如,在提交键值对形式的数据时,可利用 `urllib.parse.urlencode()` 函数完成转换工作后再将其转化为字节流传输给服务器端。 ```python from urllib.parse import urlencode from urllib.request import Request, urlopen params = {'username': 'test_user', 'password': 'secure_password!@#'} encoded_params = urlencode(params).encode('ascii') request = Request('http://example.com/login', encoded_params) with urlopen(request) as res: result = res.read().decode() print(result) ``` ##### 4. 调试工具辅助定位问题 借助外部调试工具(如 Postman 或 cURL)验证相同的 API 调用是否成功运行可以帮助确认问题是出自于代码实现还是网络环境配置方面的影响因素[^3]。 通过以上措施调整程序逻辑之后再次尝试执行操作应该能够有效规避此类异常状况的发生几率。 ### 示例代码综合应用 下面提供一段完整的示范脚本用于演示如何构建一个带有基本身份认证机制的安全 HTTPS GET 请求以及处理可能出现的各种类型的响应情况: ```python import ssl from urllib.error import URLError, HTTPError from urllib.request import build_opener, HTTPSHandler context = ssl._create_unverified_context() opener = build_opener(HTTPSHandler(context=context)) try: request = opener.open("https://insecure-site-with-self-signed-cert/") except HTTPError as http_err: status_code = http_err.code reason_phrase = http_err.reason error_message = str(http_err) print(f"An HTTP {status_code} occurred: {reason_phrase}. Details follow:\n{error_message}") except URLError as url_err: cause_of_failure = url_err.reason print(f"A connection issue arose while trying to reach the server.\nThe underlying cause was reported as follows:\n{cause_of_failure}") else: content_type_header_value = request.headers.get_content_subtype() payload_as_string = request.read().decode(encoding="UTF-8", errors="replace") if "html" in content_type_header_value.lower(): from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): pass def handle_endtag(self, tag): pass def handle_data(self, data): stripped_text = ''.join([char for char in data.strip() if ord(char) >= 32]) if len(stripped_text) > 0: print(repr(stripped_text)) parser_instance = MyHTMLParser(convert_charrefs=True) parser_instance.feed(payload_as_string) finally: try: del(opener) except NameError: pass ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值