Hello and welcome to justanswer.
Because the light comes on, but goes out intermittently the problem is not in the bulb. You likely have a poor connection at the headlamp bulb socket. If this is the case, it would be best to replace the bulb socket, as any attempts to repair the socket will likely fail. Some auto parts stores carry replacement sockets and the dealer should have replacement sockets available.