All Products
Search
Document Center

Mutual access between containers in the same pod

Last Updated: Aug 15, 2019

This example uses the Elastic Container Instance (ECI) API.

Deploy two containers in the same pod and enable communication between the containers by using the pod name and port.

This example uses two Telnet-capable images: a Redis image and an NGINX image, at the following URLs:

  1. registry.cn-hangzhou.aliyuncs.com/muya/redis:telnet
  2. registry.cn-hangzhou.aliyuncs.com/muya/nginx:telnet

Sample code

  1. # -*- coding: utf-8 -*-
  2. #! /usr/bin/python
  3. import httplib
  4. import json
  5. import urllib
  6. import uuid
  7. import time
  8. import hmac
  9. from hashlib import sha1
  10. import base64
  11. HOST = 'eci.aliyuncs.com'
  12. PORT = 80
  13. AK_ID = 'xxx'
  14. AK_SECRET = 'xxx'
  15. def generateParams(param):
  16. parameters = {}
  17. for k in param:
  18. parameters[k] = param[k]
  19. def call(params):
  20. timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
  21. parameters = {
  22. 'Format': 'json',
  23. 'Version': '2018-08-08',
  24. 'Product': 'Eci',
  25. 'AccessKeyId': AK_ID,
  26. 'SignatureVersion': '1.0',
  27. 'SignatureMethod': 'HMAC-SHA1',
  28. 'SignatureNonce': str(uuid.uuid1()),
  29. 'Timestamp': timestamp,
  30. }
  31. for k in params:
  32. parameters[k] = params[k]
  33. signature = sign(AK_SECRET, parameters)
  34. parameters['Signature'] = signature
  35. url = "/?" + urllib.urlencode(parameters)
  36. connection = httplib.HTTPConnection(HOST, PORT, 30)
  37. connection.connect()
  38. header = {
  39. 'Content-type': 'application/x-www-form-urlencoded',
  40. "Cache-Control": "no-cache",
  41. "Connection": "Keep-Alive",
  42. }
  43. connection.request('POST', url, body='', headers=header)
  44. response = connection.getresponse()
  45. result = response.read()
  46. if response.status == 200:
  47. return result
  48. else:
  49. print response.status
  50. print result
  51. exit(-1)
  52. def sign(accessKeySecret, parameters):
  53. sortedParameters = sorted(parameters.items(), key=lambda parameters: parameters[0])
  54. canonicalizedQueryString = ''
  55. for (k, v) in sortedParameters:
  56. canonicalizedQueryString += '&' + percent_encode(k) + '=' + percent_encode(v)
  57. stringToSign = 'POST&%2F&' + percent_encode(canonicalizedQueryString[1:])
  58. h = hmac.new(accessKeySecret + "&", stringToSign, sha1)
  59. signature = base64.encodestring(h.digest()).strip()
  60. return signature
  61. def percent_encode(encodeStr):
  62. encodeStr = str(encodeStr)
  63. res = urllib.quote(encodeStr.decode('UTF-8').encode('utf8'), '')
  64. res = res.replace('+', '%20')
  65. res = res.replace('*', '%2A')
  66. res = res.replace('%7E', '~')
  67. return res
  68. def CreateContainerGroup():
  69. params = {
  70. 'Action': 'CreateContainerGroup',
  71. 'RegionId': 'cn-hangzhou',
  72. 'ZoneId': 'cn-hangzhou-g',
  73. 'SecurityGroupId': 'sg-xxx',
  74. 'VSwitchId': 'vsw-xxx',
  75. 'ContainerGroupName':'test-pod-network',
  76. 'RestartPolicy':'Always',
  77. 'Cpu': 0.5,
  78. 'Memory': 1,
  79. 'Container.1.Image': 'registry.cn-hangzhou.aliyuncs.com/muya/redis:telnet',
  80. 'Container.1.Name': 'redis',
  81. 'Container.1.Cpu': 0.25,
  82. 'Container.1.Memory': 0.5,
  83. 'Container.2.Image': 'registry.cn-hangzhou.aliyuncs.com/muya/nginx:telnet',
  84. 'Container.2.Name': 'nginx',
  85. 'Container.2.Cpu': 0.25,
  86. 'Container.2.Memory': 0.5,
  87. 'Container.2.Command.1': '/bin/sh',
  88. 'Container.2.Arg.1': '-c',
  89. # telnet ${pod_name} 6379, where 6379 is the port of Redis
  90. 'Container.2.Arg.2': 'while true; do sleep 3 | telnet test-pod-network 6379; done',
  91. }
  92. ret = call(params)
  93. print ret
  94. def DescribeContainerGroup(containerGroupId):
  95. params = {
  96. 'Action': 'DescribeContainerGroups',
  97. 'RegionId': 'cn-hangzhou',
  98. 'ContainerGroupIds': json.dumps(containerGroupId),
  99. 'Status':'running',
  100. }
  101. ret = call(params)
  102. return ret
  103. if __name__ == '__main__':
  104. start = time.time()
  105. CreateContainerGroup()
  106. #eci_name = 'eci-xxx'
  107. #print json.dumps(json.loads(DescribeContainerGroup([eci_name])), sort_keys=True, indent=4, separators=(', ', ': '))
  108. elapsed = (time.time() - start)
  109. print "Time used: %f" % elapsed

Log on to the ECI console to view logs of the NGINX container. The logs show that Redis is accessible to NGINX.

test-pod-network