hoangvietfreelancer
hoangvietfreelancer

Reputation: 93

Open port on Google Colaboratory machine

I make a machine leanring on Google Colaboratory that use webserver to show data. But i can't connect with public ip and port when i run, i think because port is not open.

I tried to open port but Google Colaboratory machine run on docker

if multiple_process:
    run(host="172.28.0.2", port=80, server='paste')
else:
    run(host="172.28.0.2", port=8080, server='paste')

Upvotes: 2

Views: 13062

Answers (1)

Bob Smith
Bob Smith

Reputation: 38589

Colab backends are firewalled and cannot be directly contacted from the public Internet.

If your goal is to connect from the Colab frontend to a server running on the backend, Colab will automatically proxy requests to localhost ports. An example is available in the docs here:

https://colab.research.google.com/notebooks/snippets/advanced_outputs.ipynb#scrollTo=_7dYIo63EdgL

Reproducing the relevant snippet below, which starts an HTTP server and then loads it from the cell output:

import portpicker
import threading
import socket
import IPython

from six.moves import socketserver
from six.moves import SimpleHTTPServer

class V6Server(socketserver.TCPServer):
  address_family = socket.AF_INET6

class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
  def do_GET(self):
    self.send_response(200)
    # If the response should not be cached in the notebook for
    # offline access:
    # self.send_header('x-colab-notebook-cache-control', 'no-cache')
    self.end_headers()
    self.wfile.write(b'''
      document.querySelector('#output-area').appendChild(document.createTextNode('Script result!'));
    ''')

port = portpicker.pick_unused_port()

def server_entry():
    httpd = V6Server(('::', port), Handler)
    # Handle a single request then exit the thread.
    httpd.serve_forever()

thread = threading.Thread(target=server_entry)
thread.start()

# Display some HTML referencing the resource.
display(IPython.display.HTML('<script src="https://localhost:{port}/"></script>'.format(port=port)))

Upvotes: 7

Related Questions